简体   繁体   English

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

[英]Autolayout, async load image into uiimageview (Swift, xCode6)

Good day! 美好的一天! I have 2 problems and I hope you will help me. 我有2个问题,希望您能帮助我。

1) I have news feed in my application, that contains images. 1)我的应用程序中有新闻提要,其中包含图像。 I am using Autolayout for dynamic cells: 我正在为动态单元格使用自动版式: http://i.stack.imgur.com/DGWua.png

and I want the image to keep its ratio and to completely fill the width of the cell (with margins = 12 ). 我希望图像保持其比例并完全填充单元格的宽度( margins = 12 )。 I set constrains, cell is autoresizable , but image didn't save its ratio: 我设置了约束,单元格可以自动调整大小 ,但是图像未保存其比例:

http://i.stack.imgur.com/OSMfz.png .

What I am doing wrong? 我做错了什么?

2) The second problem, i load images asynchronously, here is my code: 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
}

All seems okay, but UITableViewCell don't resize when image is loaded and I am trying to reload cell at index path. 一切似乎都还可以,但是UITableViewCell不会在加载图像时调整大小,而我正在尝试在索引路径处重新加载单元格。
Interesting moment, that it will work if I scroll down and then come back to cell. 有趣的时刻,如果我向下滚动然后回到单元格,它将起作用。
I have similar error before and I fixed it reading this article UITableView layout messing up on push segue and return. 我之前也遇到过类似的错误,并且已阅读这篇文章的UITableView布局(在推送搜索和返回时弄乱了),将其修复 (iOS 8, Xcode beta 5, Swift) , third answer. (iOS 8,Xcode beta 5,Swift) ,第三个答案。 But it didn't help me now. 但这现在对我没有帮助。 Looks like I need to call some method to recalculate UITableViewCell , but I don't understand what. 看来我需要调用一些方法来重新计算UITableViewCell ,但是我不明白。

First question : Change UIImageView view mode from Scale to Fill to Aspect Fit (in storyboad) 第一个问题:将UIImageView视图模式从“缩放”更改为“填充”到“宽高比”(在Storyboad中)

Second question : Remove dispatch async if image is not nil and make you code look similar like this: 第二个问题:如果image不是nil,则取消调度异步,并使您的代码看起来像这样:

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

For first one in the storyboard select the image view and click on the pin icon for setting auto layout constraint and check width and height. 对于情节提要中的第一个,请选择图像视图,然后单击图钉图标以设置自动布局约束并检查宽度和高度。 it will remain the width and height constant. 它将保持宽度和高度不变。

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

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