Circular Image in UITableViewCell

空扰寡人 提交于 2021-01-29 05:18:17

问题


I'm trying to create circular Images inside of my TableViewCell but something is going wrong. I guess that the cornerRadius is to big because there is not any Image displayed with this Code. If I set the cornerRadius on 30 for example, I can see the Images rounded but not in a clear circle .Why is this not working ?

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "QuestionLine")
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "QuestionLine")


    let user = users[indexPath.row]
     cell?.textLabel?.text = user.question
     cell?.detailTextLabel?.text = user.name

     let image = UIImage(named: user.profilePicture)
     cell?.imageView?.image = image
     cell?.imageView?.layer.cornerRadius = (image?.size.width)! / 2
     cell?.imageView?.clipsToBounds = true

    return cell!

}

回答1:


Try this code

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "QuestionLine")
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "QuestionLine")


    let user = users[indexPath.row]
    cell?.textLabel?.text = user.question
    cell?.detailTextLabel?.text = user.name

    let image = UIImage(named: user.profilePicture)
    cell?.imageView?.image = image

    cell?.imageView?.layer.cornerRadius = (cell?.imageView?.frame.size.width)! / 2
    cell?.imageView?.layer.masksToBounds = true
    cell?.imageView?.layer.borderColor = colour.cgColor
    cell?.imageView?.layer.borderWidth = 1

    return cell!
}



回答2:


The UITableViewCell's imageView will be sized to the height of the cell, If you want to customize the size of imageView try the below code.

   let image = UIImage(named: user.profilePicture)
    cell?.imageView?.image = image

    let itemSize = CGSize.init(width: 40, height: 40) // your custom size
    UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale);
    let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
    cell?.imageView?.image!.draw(in: imageRect)
    cell?.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!;
    UIGraphicsEndImageContext()

    cell?.imageView?.layer.cornerRadius = (itemSize.width) / 2
    cell?.imageView?.clipsToBounds = true



回答3:


First make sure your image height and width is equal, then replace last 3 lines of code with these lines-

 cell?.imageView?.layer.cornerRadius = (image?.frame.size.width)!  /  2
 cell?.imageView?.masksToBounds = true

 return cell!


来源:https://stackoverflow.com/questions/50377557/circular-image-in-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!