通过UITableViewCell创建UIImage clipsToBound

时间:2017-12-18 10:56:40

标签: ios swift

我有一个带有静态表格单元格的UITableViewController

我正在尝试使用UIImageView和此图像clipToBounds创建一个单元格,但它不起作用。

这是我想要做的一个示例。

enter image description here

但是当我制作UITableView并将UIImage clipToBounds 设置为 TRUE

结果是:

enter image description here

我只是需要一种方法来使UIImageView像第一张图片一样用UITableView Cell做到这一点吗?

这是我的UIImageView约束:

enter image description here

这是我的代码:

class ProfileTableViewController: UITableViewController {

    @IBOutlet weak var userImage: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()



        // image view 

       self.userImage.layer.cornerRadius = self.userImage.frame.width / 2
       self.userImage.clipsToBounds = true




    }

// MARK: - 表视图数据源

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 3
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    var number = 0

    if section == 0
    {
        number = 1
    }else if section == 1
    {
        number = 4
    }else if section == 2
    {
        number = 1
    }

    return number 
}


override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 100 
}

}

5 个答案:

答案 0 :(得分:1)

为什么clipsToBounds = true? 如果图像必须是outside单元格,那么我想你想要反其道而行:

yourView.clipsToBounds = false

答案 1 :(得分:1)

只需为图像视图创建出口,使其角半径为宽度/ 2(确保高度和宽度相同)并使剪辑绑定为true。例如:

imageView = imageView.frame.size.width/2;
imageView.clipsToBounds = true;

答案 2 :(得分:1)

当我添加此方法并添加自定义Section标头

时,我找到了解决方案

并给它clipToBounds = false

问题解决了

我刚刚补充道:

  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.clipsToBounds = false

        return view
    }

并且它完美地工作:))

感谢所有人试图帮助我

答案 3 :(得分:0)

这可能会解决您的问题。在indexPath

中的行的单元格中
let height = CGFloat(cell.frame.size.height-10)
let leading = (cell.frame.size.width - height)/2
let top = CGFloat(18)

let myImage = UIImageView(frame: CGRect(x: leading, y: top, width: height, height:height))
myImage.layer.masksToBounds = true
myImage.layer.cornerRadius = (height)/2
cell.contentView.addSubview(myImage)

// OR

cell.myImage.layer.cornerRadius = cell.myImage.frame.width / 2
cell.myImage.clipsToBounds = true

答案 4 :(得分:0)