如何在iOS TableViewCell上实现圆形图像?

时间:2018-04-06 18:34:46

标签: swift uitableview uiimageview kingfisher

我试图以这种方式将圆形图像附加到我的自定义表格单元格中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let content : Content = contentsCollection.contents[indexPath.row]
    let channel : Channel = contentsCollection.channel(withId: content.channel!.id)

    let cell = tableView.dequeueReusableCell(withIdentifier: "ContentCell") as! ContentCell
    cell.layoutSubviews()

    let channelPicture = URL(string: channel.picture)

    cell.channelImageView.kf.setImage(with: channelPicture)

    //Rounded image
    cell.channelImageView.layer.cornerRadius = cell.channelImageView.frame.height/2    

    return cell
}

问题是,当第一次显示视图控制器时,图像视图仍然是方形。只有“隐藏”单元格具有圆形图像视图。

似乎是这篇文章中记录的问题:https://medium.com/@adinugroho/circular-uiimageview-in-uitableview-cell-e1a7e1b6fe63

但我无法为我的实施找到解决方法。

3 个答案:

答案 0 :(得分:4)

我认为缺少clipsToBounds

请参阅https://www.appcoda.com/ios-programming-circular-image-calayer/

我创建了一个RoundImageView类。

class RoundImageView: UIImageView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = self.frame.height/2
        self.clipsToBounds = true
    }
}

在故事板上实现这个。

enter image description here

适合我。

Alternativ:cell.channelImageView.clipsToBound = true应该有用。

答案 1 :(得分:0)

您可以使用

进行UIImageView四舍五入
imageView.layer.cornerRadius = 10
imageView.layer.masksToBounds = true

另一种方法是将CAShapeLayer添加到UIView

let mask = CAShapeLayer()
mask.path = UIBezierPath(ovalIn: view.bounds).cgPath
let imageLayer = CAShapeLayer()
imageLayer.mask = mask
imageLayer.frame = view.bounds
imageLayer.contents = image.cgImage
view.layer.addSublayer(imageLayer)

答案 2 :(得分:0)

就我的具体情况而言,只有这样才能正常运作:

cell.layoutIfNeeded()

此行将在cornerRadius选项之前。

希望这可以帮助其他同样的问题。