UITableViewAutomaticDimension + AFNetworking

UITableViewAutomaticDimension + AFNetworking

我正在从 API 加载图像,它们具有不同的高度并显示在包含其他类型单元格的 UITableView 中(我使用 UITableViewAutomaticDimension 的原因)

我想使用图像高度显示(或重新加载)包含图像的单元格,以避免失真。

我尝试了不同的解决方案,但我很难让它工作? 关于如何解决此问题的任何提示或建议?

谢谢

编辑:

我在这里上传了一个示例项目https://github.com/LucasCoelho/ImageLoading

崩溃错误是

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 9 beyond bounds [0 .. 8]'

我认为这可能与那些冲突的 NSAutolayoutConstraints 有关

(
    "<NSLayoutConstraint:0x7f85db176750 V:[UIImageView:0x7f85db17a090(72)]>",
    "<NSLayoutConstraint:0x7f85db18ca90 V:|-(0)-[UIImageView:0x7f85db17a090]   (Names: '|':UITableViewCellContentView:0x7f85db179f70 )>",
    "<NSLayoutConstraint:0x7f85db18cb80 V:[UIImageView:0x7f85db17a090]-(0)-|   (Names: '|':UITableViewCellContentView:0x7f85db179f70 )>",
    "<NSLayoutConstraint:0x7f85db197e50 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7f85db179f70(128)]>"
)

首先,您需要为 imageView 添加高度约束,并从 UITableViewCell 子类创建对它的引用。

class TableViewCell: UITableViewCell {
      @IBOutlet weak var imageView: UIImageView!
      @IBOutlet weak var imageViewHeightConst: NSLayoutConstraint!
}

然后利用UIImageView+AFNetworking.h方法:

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
          placeholderImage:(UIImage *)placeholderImage
                   success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                   failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;

在成功块中,您需要将下载的图像设置为您的 imageView 并更新 imageViewHeightConst 常量 属性.

imageView.image = image
imageViewHeightConst.constant = image.size.height

您还需要一种方法来通知您的 table 视图图像已经下载并且 table 视图应该更新。所以你可以使用委托模式来解决这个问题。在委托方法的实现中,您可以使用以下代码更新 table 视图:

 tableView.beginUpdates()
 tableView.endUpdates() 

最终您的单元格子类将类似于此:

@objc protocol TableViewCellDelegate {
    func tableViewCell(cell: UITableViewCell, didLoadImage: UIImage)
}

class TableViewCell: UITableViewCell {
    @IBOutlet weak var photoImageView: UIImageView!
    @IBOutlet weak var imageViewHeightConst: NSLayoutConstraint!

    weak var delegate: TableViewCellDelegate?
}

extension TableViewCell {

    func configureCellForURL(url: NSURL, placeholderImage: UIImage) {
        let request = NSURLRequest(URL: url)
        photoImageView.setImageWithURLRequest(request, placeholderImage: placeholderImage, success: { [weak self] (request, response, image) -> Void in

            self?.photoImageView?.image = image
            self?.imageViewHeightConst?.constant = image.size.height
            self?.delegate?.tableViewCell(self!, didLoadImage: image)

        }) { (request, response, error) -> Void in

        }
    }
}