UITableViewCell中的圆形图像

时间:2018-05-16 18:14:54

标签: ios swift uitableview uiimageview

我正在尝试在TableViewCell中创建圆形图像,但出了点问题。我想cornerRadius是大的,因为这个代码没有显示任何图像。例如,如果我将cornerRadius设置为30,我可以看到图像已圆整但不是清晰的圆圈。为什么这不起作用?

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!

}

3 个答案:

答案 0 :(得分:1)

试试此代码

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!
}

答案 1 :(得分:0)

UITableViewCell的imageView将根据单元格的高度调整大小。如果要自定义imageView的大小,请尝试以下代码。

   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

答案 2 :(得分:0)

首先确保您的图像高度和宽度相等,然后用这些行替换最后3行代码 -

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

 return cell!