user979331
user979331

Reputation: 11961

Swift resize uitablecell image

I just set my UITableCell linebreak to byWordWrapping and add this method:

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

Now My UITableCell Images are massive, what is the best way to resize them or have the images aspect to fit?

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "commentsCell", for: indexPath)

        cell.textLabel?.numberOfLines = 0
        cell.textLabel?.lineBreakMode = .byWordWrapping

        cell.detailTextLabel?.numberOfLines = 0
        cell.detailTextLabel?.lineBreakMode = .byWordWrapping

        if((self.array[indexPath.row]["profileImg"] as! String) == "")
        {
            cell.textLabel?.text = (self.array[indexPath.row]["username"] as! String)
            cell.detailTextLabel?.text = (self.array[indexPath.row]["comment"] as! String)
            cell.imageView?.image = UIImage(named: "default.png")
        }
        else
        {
            let imgUrl = URL(string:"http://auxpod.com/uploads/" + (self.array[indexPath.row]["profileImg"] as! String))

            Alamofire.request(imgUrl!).responseImage { response in
                DispatchQueue.main.async {
                    if let image = response.result.value {
                        cell.textLabel?.text = (self.array[indexPath.row]["username"] as! String)
                        cell.detailTextLabel?.text = (self.array[indexPath.row]["comment"] as! String)
                        cell.imageView?.image = image
                    }
                }
            }
        }

        return cell

    }

Upvotes: 0

Views: 47

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

1-

Don't load the image inside cellForRowAt as it keeps download the image every scroll so use SDWebImage that caches it after first download

2-

Create a custom cell class , hook the the height constraint of the imageView and change it according to the required aspect ratio

imageViewH.constant = imageRealHeight * imageCellWidth / imageRealWidth

Upvotes: 1

Related Questions