自定义UITableViewCell的UIImageView在点击之前不会适合

时间:2016-12-29 12:19:22

标签: ios iphone swift uitableview uiimageview

我正在通过斯坦福大学的cs193p。作业4让我们创建一个自定义的UITableVIewCell,并将一张图片从网页加载到单元格内的UIImageView中。

我的UIImageView和我的Cell将他们的内容模式设置为故事板上的Aspect Fit。并且在自动布局上将ImageView设置为拥抱该单元格。 然而,当图片首次加载时,它会从UIImageView中流出。当我点击它时,它将正确适合。

我尝试在分配图像之前在代码中设置内容模式,但这也无效。我也尝试在分配图像后立即调用layoutSubviews()和setNeedsLayout,虽然这有助于实际显示图像(而不是在用户单击单元格之前没有显示任何内容),但在用户单击它之前它仍然显示错误的大小

This is the UIImageView's constraints

这是单元格的代码:

import UIKit


class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var pictureView: UIImageView!

    var pictureURL: URL? {
        didSet {
            fetchImage()
        }
    }

    fileprivate func fetchImage() {
        if let url = pictureURL {
            pictureView.image = nil
            let queue = DispatchQueue(label: "image fetcher", qos: .userInitiated)
            queue.async { [weak weakSelf = self] in 
                do {
                    let contentsOfURL = try Data(contentsOf: url)

                    DispatchQueue.main.async {
                        if url == self.pictureURL {
                            weakSelf?.pictureView?.image = UIImage(data: contentsOfURL)
                            weakSelf?.layoutSubviews()
                            print("loaded")
                        }
                    }
                } catch let exception {
                    print(exception.localizedDescription)
                }
            }
        }
    }
}

这是在TableViewController上加载单元格的代码:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        switch indexPath.section {
        case 0:
            cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath)
            if let imageCell = cell as? ImageTableViewCell {
                imageCell.pictureURL = tweet?.media[indexPath.row].url
        // other stuff not programmed yet
        }
        return cell

给我单元格高度的代码:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 && tweet != nil {
            let media = tweet?.media[indexPath.row]
            return tableView.frame.width / CGFloat(media!.aspectRatio)
        }
        return UITableViewAutomaticDimension
    }

我很遗憾粘贴所有这些代码,但我不知道问题出在哪里,所以我把所有可能与之相关的内容都放在一起。

2 个答案:

答案 0 :(得分:0)

您应首先设置content mode,然后设置imageview的框架,这样一旦您尝试在awakeFromNib tableview subclass中设置内容模式,在将图像设置为它之前cellforrowatindexpath

或者您可以从界面构建器(来自故事板!)设置内容模式 - >选择你的imageview - >来自属性检查员 - >选择模式(在视图下)到Aspect fit

答案 1 :(得分:0)

好吧,在关于reddit的回答之后,我删除了表视图控制器并重新创建它,再次设置所有出口。它有效,我想这是Xcode中的一个问题?

因此,如果您遇到类似问题,请尝试重新制作故事板。

相关问题