簡體   English   中英

UITableViewCell中的圓形圖像

[英]Circular Image in UITableViewCell

我正在嘗試在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!

}

試試這個代碼

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

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

首先請確保您的圖片高度和寬度相等,然后用這些行替換最后3行代碼-

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

 return cell!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM