繁体   English   中英

带有UIImageView的快速自定义UITableViewCell。 需要将单元格调整为图像高度

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

我正在尝试制作应用程序,它将在表格视图中显示图像。 我有带有图像视图的自定义单元格。 它仅必须从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
    }

我对图像设置了“宽高比”,但结果却很奇怪。 图像超出了单元的边界。 也许我需要设置一些限制...我不知道。

结果:

结果

但我需要这个:

不错的结果

如果要异步加载图像:

加载并设置新的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一起使用,则需要正确设置约束( image )。 (对于正确的宽度和高度,建议您使用宽高比)

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

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

屏幕截图

也许此屏幕截图会为您提供帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM