Xcode Imageview Aspect Fit Remove Extra Space

前端 未结 2 681
星月不相逢
星月不相逢 2020-12-11 04:08

I have an imageview inside a UITableViewCell.

Imageview with Aspect Fit creates a lot of extra space in the top and bottom if the image is large. The extra space (g

2条回答
  •  执念已碎
    2020-12-11 04:54

    The above answer doesn't work when using UITableViewAutomaticDimension.

    In general the problem is that in the tableView function "cellForRowAt indexPath" tableView hasn't yet laid out cell and it's subviews.

    So one solution to this problem is using a subclass of UITableView:

    class MyUITableView: UITableView {
    
        // Makes real device cell width available in "cellForRowAt indexPath"
        override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell {
            let cell = super.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
            cell.frame.size.width = self.frame.size.width
            cell.layoutIfNeeded()
            return cell
        }
    }
    

    Now you can use any of the solutions in for instance the link in Md Rais' comment. As an example my own code:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ViewCell
    
        if let attach = eventsByDay[indexPath.section][indexPath.row].attachPhoto {
            let cellWidth = cell.attachPhoto.frame.size.width
            let scale = cellWidth / attach.size.width
            let size = CGSize(width: cellWidth, height: attach.size.height * scale)
    
            UIGraphicsBeginImageContextWithOptions(size, true, 0.0)             
            attach.draw(in: CGRect(origin: CGPoint.zero, size: size))
            cell.attachPhoto.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        } else {
            cell.attachPhoto.image = nil
        }
    
        // ...
        return cell
    }
    

提交回复
热议问题