圆形图像在第一次刷新表时为正方形

时间:2018-06-29 17:50:41

标签: 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属性。正确重新加载后,便会设置属性。

但是,当单元格移出视野或通过获取新信息进行更新(.reloadData()不执行任何操作)时,单元格中的图像是圆形的。

还有其他问题,但是每个人都重复说,您需要设置cornerRadius属性和masksToBounds。这绝对不会帮助解决我的问题,因为这些属性已明确设置。

我也尝试使用图像层代码对UITableViewCell进行扩展,但结果完全相同。

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

enter image description here

如有任何疑问,请询问

1 个答案:

答案 0 :(得分:0)

实际上,在您设置其图层的imageView's frame时,.zerocornerRadius。如果您有imageView的固定大小,则可以将cornerRadius设置为width的一半,这样就可以正常工作。如下所示,

cell.imageView?.layer.cornerRadius = 50 //If width&height is 100 fix.

第二个选项是通过cornerRadius overriding方法设置正确的layoutSubviews,因为此方法可确保您的cell布局正确,并且您将获得正确的{ frame的{​​1}}

subViews