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

我试图做的应用程序,这将显示图像在表视图。 我有图像视图的自定义单元格。 它只需要从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 } 

我设置“方面适合”形象,我得到奇怪的结果。 图像超出了单元格的边界。 也许我需要设置一些限制…我不知道。

结果:

它的结果

但是我需要这个:

很好的结果

如果你想加载图像asynchronous:

加载并设置新的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) } } } 

如果你想使用UITableViewAutomaticDimension dinamic表,那么你需要正确设置你的约束( 图像 )。 (对于正确的宽度和高度,我build议你使用宽高比)

使用静态表视图,您应该实现optional func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat ,并手动计算单元大小。

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

截图

也许这个截图会帮助你