【发布时间】:2022-01-06 04:09:33
【问题描述】:
以下答案中的编辑代码
我想要什么
图片大小正确,位置正确
我得到了什么
当我滚动时,一堆图像随机出现在各处
我浏览了很多答案,但仍然没有找到解决问题的方法。对于每个人来说,这似乎常常是一个不同的问题,而且这里的大多数问题都在 Objective-C 中并没有帮助。我发现从一种转换到另一种很困难。
我将只展示我的表格视图函数并解释我的代码,也许有人可以找出问题或帮助我找出问题来自己解决。
------------------------------------------ ---------------------------------------
说明
并非所有新闻项目(单元格)都包含图片。如您所见(在下面的第一个函数中),我循环浏览各个部分和嵌套单元格,如果新闻项目包含图片if newslists[i][j] != "None,则显示该图像。至此就是熟悉的代码了,看教程here
在第二个函数中,我再次遍历部分和单元格,直到找到应该包含图像的单元格。然后我更改此单元格的高度,以便图像适合其中。
差不多就是这样…… 有什么想法吗?
------------------------------------------ ---------------------------------------
CellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! UITableViewCell
if newslists[indexPath.section][indexPath.row].imageURL != "None"{
let urlString = newslists[indexPath.section][indexPath.row].imageURL
let imgURL = NSURL(string: urlString)
cell.imageView?.image = UIImage(named: "first") // placeholder
if let img = imageCache[urlString] {
cell.imageView?.image = img
println("loaded from cache")
}
else {
let request: NSURLRequest = NSURLRequest(URL: imgURL!)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)
self.imageCache[urlString] = image
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
println("succesfully downloaded image")
println("size of cache is \(self.imageCache.count)")
}
})
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
}
cell.backgroundColor = UIColor(red: 52/255, green: 138/255, blue: 169/255, alpha: 1.0)
return cell
}
我还有一个功能可能会导致问题,但我对此表示怀疑:
HeightForRowAtIndexPath
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if newslists[indexPath.section][indexPath.row].imageURL != "None"{
println("Expanding cell for \(indexPath.section) \(indexPath.row)")
return 190.0
}
return 70.0
}
【问题讨论】:
标签: ios swift uitableview asynchronous uiimageview