Swift,使用 UIImageView 自定义 UITableViewCell。需要将单元格调整为图像高度

Swift, custom UITableViewCell with UIImageView. Need to resize cell to image height

我正在尝试制作应用程序,它将在 table 视图中显示图像。 我有带图像视图的自定义单元格。它只需要从 url 下载图像数据:

@IBOutlet weak var tweetImage: UIImageView!
var imageData : MediaItem? { didSet { updateUI() }}

func updateUI(){
    tweetImage.image = nil
    if let url = imageData?.url {
        if let data = NSData(contentsOfURL: url) {
            tweetImage.image = UIImage(data: data)
        }
    }
}

我需要在下载后更改单元格高度。它必须等于图像的高度。我在 viewController:

中设置了自动尺寸
override func viewDidLoad() {
        super.viewDidLoad()
        tableView.estimatedRowHeight = tableView.rowHeight
        tableView.rowHeight = UITableViewAutomaticDimension
    }

我将 "aspect fit" 设置为图像,我得到了奇怪的结果。图像超出了单元格的边界。也许我需要设置一些限制...我不知道。

结果:

但我需要这个:

如果您想将动态 table 与 UITableViewAutomaticDimension 一起使用,则需要正确设置约束 (image)。 (为了正确的宽度和高度,我建议你使用纵横比)

对于静态 table 视图,您应该实施 optional func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat,并手动计算单元格大小。

当然,您需要为单元格中的图像设置约束条件

也许这张截图会对你有所帮助

如果你想异步加载图片:

加载并设置新的 UIImage 后,您可以通过 UITableView 函数重新加载特定单元格:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

在你的 UIViewController 中:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedRowHeight = tableView.rowHeight
    tableView.rowHeight = UITableViewAutomaticDimension
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "imageDidLoadNotification:", name:"CellDidLoadImageDidLoadNotification", object: nil)
}

func imageDidLoadNotification(notification: NSNotification) {
    if  let cell = notification.object as? UITableViewCell
        let indexPath = tableView.indexPathForCell(cell) {
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    }
}

在你的 UITableViewCell 中

func updateUI(){
    tweetImage.image = nil
    if let url = imageData?.url {
        if let data = NSData(contentsOfURL: url) {
            tweetImage.image = UIImage(data: data)
            NSNotificationCenter.defaultCenter().postNotificationName("CellDidLoadImageDidLoadNotification", object: self)
        }
    }
}