裁切成圆形的cell.imageView?

问题描述 投票:0回答:2

无法裁剪cell.imageView?来圈出。

我在很多论坛上都没找到。

我在标准单元格(非自定义)中使用tableView

我的代码:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "channelCell", for: indexPath) 
    cell.accessoryType = .disclosureIndicator
    cell.imageView?.layer.cornerRadius = cell.frame.size.height / 2
    cell.imageView?.clipsToBounds = true
    cell.imageView?.kf.setImage(with: URL(string: channels[indexPath.row].userUrlImage))
    return cell
}

我得到此图像,在第二个用户上检查该图像

enter image description here

UPD。

enter image description here

ios swift uiimageview tableview cell
2个回答
0
投票

您应在:之前为图像视图设置框架:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "channelCell", for: indexPath) 
    cell.accessoryType = .disclosureIndicator
    cell.imageView?.frame = CGRect(x: 0, y: 0, width: cell.frame.size.height, height: cell.frame.size.height)
    cell.imageView?.contentMode = .scaleToFill
    cell.imageView?.layer.cornerRadius = cell.frame.size.height / 2
    cell.imageView?.clipsToBounds = true
    cell.imageView?.kf.setImage(with: URL(string: channels[indexPath.row].userUrlImage))
    return cell
}

0
投票

[在您填充单元格时,您的单元格尚未布置框架。1)一种方法是调用layoutIfNeeded()然后设置转角半径,等于cell.imageView?.layer.cornerRadius = cell.imageView?.bounds.frame.height / 2但这从性能的角度来看并不是最好的,因为您创建了多余的布局通道。2)另一种方法是创建UITableViewCell的子类并覆盖它的layoutSubviews。然后在layoutSubviews中设置拐角半径。3)从可重用性的角度来看,最简单,最好的方法是创建UIImageView的子类并覆盖布局子视图。这是第三种方法的代码

/*
Create custom UITableViewCell and use CircledImageView instead of UIImageView.
*/
class CircledImageView: UIImageView {
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.bounds.size.height / 2
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.