我的 UITableView
连接了一个搜索栏。
这是迄今为止我的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SongPicker.dequeueReusableCell(withIdentifier: "cell")!
// Image
cell.imageView?.image = songHandler.songItems[indexPath.row].songImage?.cropToBounds()
cell.imageView?.layer.cornerRadius = cell.imageView!.frame.width / 2
cell.imageView?.layer.masksToBounds = true
cell.imageView?.layer.borderWidth = 3
cell.imageView?.layer.borderColor = UIColor.lightGray.cgColor
// Song name
cell.textLabel?.text = songHandler.songItems[indexPath.row].songName
// Artist name
cell.detailTextLabel?.text = songHandler.songItems[indexPath.row].songArtist
return cell
}
(SongPicker
是我的表格)
通过打印 cell.imageView?.layer
的结果,我可以看到,当图像首次加载时,它们没有在图像中设置 cornerRadius
属性实例。正确重新加载后,属性即被设置。
但是,当单元格移出 View 或通过获取新信息进行更新时(.reloadData()
不执行任何操作),单元格中的图像是圆形的。
关于此还有其他问题,但每个人都重复说您需要设置 cornerRadius
属性和 masksToBounds
。这绝不有助于解决我的问题,因为这些属性已明确设置。
我也尝试使用图像层代码对 UITableViewCell
进行扩展,但结果完全相同。
为什么我的图像一开始是方形的,如何轻松解决这个问题?
如有任何问题请询问
最佳答案
实际上,当您设置其图层的cornerRadius
时,imageView的框架
是.zero
。如果您的imageView
有固定大小,那么您可以将cornerRadius
设置为width
的一半,这样就可以正常工作。如下所示,
cell.imageView?.layer.cornerRadius = 50 //If width&height is 100 fix.
第二个选项是通过覆盖
layoutSubviews
方法来设置正确的cornerRadius
,因为此方法可确保您的cell
> 已列出其大小,您将获得 subViews
的正确 frame
class MyTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.layer.cornerRadius = self.imageView!.frame.width / 2
self.imageView?.layer.masksToBounds = true
self.imageView?.layer.borderWidth = 3
}
}
关于ios - 第一次刷新表格时,圆形图像是方形的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107072/