自动布局,将图像异步加载到 uiimageview (Swift, xCode6)

Autolayout, async load image into uiimageview (Swift, xCode6)

美好的一天!我有两个问题,希望你能帮助我。

1) 我的应用程序中有新闻提要,其中包含图像。 我正在为动态单元格使用自动布局:

并且我希望图像保持其比例并完全填满单元格的宽度(margins = 12)。 我设置了约束,单元格是 autoresizable,但图像没有保存它的比例:

我做错了什么?

2) 第二个问题,我异步加载图片,这里是我的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: EventCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as EventCell
    var rowData: NSDictionary = tableData[indexPath.row] as NSDictionary
    cell.titleButton.setTitle(rowData["title"] as? String, forState: UIControlState.Normal)
    cell.titleButton.addTarget(self, action: "openWebSite:", forControlEvents: UIControlEvents.TouchUpInside)
    cell.titleButton.tag = indexPath.row
    cell.descriprionLabel.text = rowData["description"] as? String
    var urlString = rowData["image"] as String
    var image = imageCache[urlString]
    if( image == nil ) {
        var imgURL = NSURL(string: urlString)

        // Download an NSData representation of the image at the URL
        var request: NSURLRequest = NSURLRequest(URL: imgURL!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
            if error == nil {
                image = UIImage(data: data) // data -> image
                // Store the image in to our cache
                self.imageCache[urlString] = image // save in our dictionary
                if let cellToUpdate : EventCell = tableView.cellForRowAtIndexPath(indexPath) as? EventCell {
                    self.table.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
                }
            }
            else {
                println("Error: \(error.localizedDescription)")
            }
        })
    } else {
        dispatch_async(dispatch_get_main_queue(), {
            if let cellToUpdate : EventCell = tableView.cellForRowAtIndexPath(indexPath) as? EventCell  {
                cellToUpdate.img.image = image
            }
        })
    }
    cell.selectionStyle = UITableViewCellSelectionStyle.None;
    cell.contentView.setNeedsLayout(); // autolayout bug solution
    cell.contentView.layoutIfNeeded(); // autolayout bug solution
    return cell
}

一切似乎没问题,但 UITableViewCell 加载图像时不调整大小,我正在尝试重新加载索引路径中的单元格。
有趣的时刻,如果我向下滚动然后返回单元格,它将起作用。
我以前有过类似的错误,我阅读这篇文章UITableView layout messing up on push segue and return. (iOS 8, Xcode beta 5, Swift),第三个答案修复了它。但它现在对我没有帮助。看起来我需要调用一些方法来重新计算 UITableViewCell,但我不明白是什么。

第一个问题:将 UIImageView 视图模式从“缩放”更改为“填充”到“纵横比适合”(在故事板中)

第二个问题:如果图像不是 nil,则删除分派异步并使您的代码看起来像这样:

if( image == nil ) {
...
}
else {
    cell.img.image = image       
}

对于故事板中的第一个 select 图像视图并单击图钉图标以设置自动布局约束并检查宽度和高度。 它将保持宽度和高度不变。