【问题标题】:Circular Image in UITableViewCellUITableViewCell 中的圆形图像
【发布时间】:2018-10-26 21:39:09
【问题描述】:

我正在尝试在 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!

}

【问题讨论】:

  • 你应该使用 imageView 帧大小而不是图像大小
  • 好的,但这没有帮助:/
  • 编辑您的问题并添加您的实际代码

标签: ios swift uitableview uiimageview


【解决方案1】:

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】:

    试试这个代码

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多