【发布时间】:2015-05-11 12:19:06
【问题描述】:
美好的一天!我有2个问题,希望你能帮助我。
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,但我不明白是什么。
【问题讨论】:
-
将
.reloadRows...调用封装在self.table.beginUpdates()和self.table.endUpdates()之间。
标签: ios swift uiimageview autolayout