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

标签 ios swift uitableview uiimageview uikit

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

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

结果:

result of it

但我需要这个:

nice result

最佳答案

如果你想异步加载图片:

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

关于ios - Swift,自定义 UITableViewCell 和 UIImageView。需要将单元格调整为图像高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805341/

相关文章:

ios - 将 UITableView 滚动到顶部无法正确滚动

ios - 模拟器在 UIImageView 中显示我的图像,但在我的真实 iPhone 上却没有

ios - Getting Error Receiver for class message 是前向声明

html - iOS 将 HTML 实体解码为字符串

Swift 在 Storyboard 中设置 UIButton setBorderColor

ios - 带有 NSFetchedResultsController 的 UITableView 不会第二次加载

ios - 如何在iOS中制作通用框架?

ios - 查找具有匹配键的字典值的总和

swift - 定义像 Swift 中的类一样对待的结构

objective-c - 如何使用自动布局以编程方式创建 UITableView?