如何解决如果在应用程序运行时更改单元格中的图像,则点击该单元格将压缩/扩展图像我怎样才能解决这个问题?
这里的问题代码,我有一个非常简单的tableView和static tableViewCell, (我在tableViewCell中设置了随机图片) 我有一个按钮,它更改tableViewCell图像(单击一次),然后在单元格上单击 结果:您的图像尺寸在单元格中发生了变化,为什么?
class ViewController: UIViewController {
var btn: UIButton = {
let obj = UIButton()
obj.addTarget(self,action: #selector(change),for: .touchUpInside)
obj.backgroundColor = .red
return obj
}()
private lazy var tableView: UITableView = {
let obj = UITableView(frame: .zero,style: .insetGrouped)
obj.translatesAutoresizingMaskIntoConstraints = false
obj.delegate = self
obj.dataSource = self
obj.backgroundColor = .blue
return obj
}()
let cell: UITableViewCell = {
let obj = UITableViewCell()
obj.imageView?.image = #imageLiteral(resourceName: "client")
return obj
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(btn)
btn.frame = CGRect.init(x: 23,y: 24,width: 100,height: 32)
self.view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),tableView.topAnchor.constraint(equalTo: self.view.topAnchor,constant: 100),tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),])
}
@objc func change() {
self.cell.imageView?.image = UIImage(systemName: "\(Int.random(in: 0...10)).circle")
}
}
extension ViewController: UITableViewDelegate,UITableViewDataSource {
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cell
}
}
解决方法
当您首次设置UITableViewCell
属性时,默认的.imageView
将创建其.image
。在内部UIKit
的内部使用您正在设置的图像的大小以及行的高度来确定该图像视图的大小。
要获得一致的尺寸,您需要将图像调整为相同的尺寸。
不过,您所展示的方法很奇怪。除非您只是尝试进行测试,否则使用自定义视图而不是仅使用一行的表视图会更好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。