[英]Autolayout, async load image into uiimageview (Swift, xCode6)
美好的一天! 我有2个问题,希望您能帮助我。
1)我的应用程序中有新闻提要,其中包含图像。 我正在为动态单元格使用自动版式:
我希望图像保持其比例并完全填充单元格的宽度( margins = 12
)。 我设置了约束,单元格可以自动调整大小 ,但是图像未保存其比例:
。
我做错了什么?
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布局(在推送搜索和返回时弄乱了),将其修复。 (iOS 8,Xcode beta 5,Swift) ,第三个答案。 但这现在对我没有帮助。 看来我需要调用一些方法来重新计算UITableViewCell
,但是我不明白。
第一个问题:将UIImageView视图模式从“缩放”更改为“填充”到“宽高比”(在Storyboad中)
第二个问题:如果image不是nil,则取消调度异步,并使您的代码看起来像这样:
if( image == nil ) {
...
}
else {
cell.img.image = image
}
对于情节提要中的第一个,请选择图像视图,然后单击图钉图标以设置自动布局约束并检查宽度和高度。 它将保持宽度和高度不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.