问题
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