ios - 第一次刷新表格时,圆形图像是方形的

标签 ios swift uitableview

我的 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 进行扩展,但结果完全相同。

为什么我的图像一开始是方形的,如何轻松解决这个问题?

enter image description here

如有任何问题请询问

最佳答案

实际上,当您设置其图层的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/

相关文章:

ios - 部分显示 UITableViewController 就像 Facebook iPhone 应用程序

ios - 快速扩展Tableview单元格如何调整高度

ios - UIScrollView 内的水平 UIStackView 不滚动

ios - 弹出 View 选择图像

xcode - Swift:如何子类化 UIButton?

swift - UITextField 在 Swift 中设置最大字符长度

ios - 如何让我的 searchBar TableView 执行 segue

iOS:使用 UIBlurEffect 的过渡动画?

c# - 将 .net 库集成到 Objective C iOS 应用程序中

swift - Swift 3.0 中浮点元素数组的扩展