How to change UITableViewCell Image to Circle in UITableView

前端 未结 11 1488

My code works for the most part.

  • The issue I am having is the images start out as square, and change to circle when I scroll the table or refresh it.

11条回答
  •  被撕碎了的回忆
    2021-02-12 12:52

    In order if anyone having this problem, here is the solution in

    Swift

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:ContactCellTableViewCell? = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as? ContactCellTableViewCell
    
    
    
        var contact : ContactStruct
        image = searchResults[indexPath.row]
        let newImage = resizeImage(image, toTheSize: CGSizeMake(70, 70))
        var cellImageLayer: CALayer?  = cell?.imageView.layer
        cellImageLayer!.cornerRadius = 35
        cellImageLayer!.masksToBounds = true
        cell?.imageView.image = newImage
    
    
        return cell!
    }
    

    As you might noticed the 35 hardcode is basically half of the image size which is 70 in here. And here is the resize function:

    func resizeImage(image:UIImage, toTheSize size:CGSize)->UIImage{
    
    
        var scale = CGFloat(max(size.width/image.size.width,
            size.height/image.size.height))
        var width:CGFloat  = image.size.width * scale
        var height:CGFloat = image.size.height * scale;
    
        var rr:CGRect = CGRectMake( 0, 0, width, height);
    
        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        image.drawInRect(rr)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return newImage
    }
    

    Note: I am using a custom cell class as below:

    import UIKit
    
    class ContactCellTableViewCell: UITableViewCell {
    
        @IBOutlet weak var nameLabel: UILabel!
        @IBOutlet weak var contactImage: UIImageView!
        @IBOutlet weak var phoneLabel: UILabel!
    
    
    
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
        }
    
        override func setSelected(selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            // Configure the view for the selected state
        }
    }
    

    It really took me a while to figure this one out. The images become rounded after scrolling at first, but now using this code you are going to have the rounded images inside the cell from beginning. Hope it helped anyone.

提交回复
热议问题