【发布时间】:2017-01-09 23:39:23
【问题描述】:
我是 Swift 的新手。我正在尝试在我的表格视图中显示图像。我正在关注这个tutorial。
在我的UITableView中,如图所示tutorial。我将图像存储在缓存中。如果 tableview 只有一个部分,这很好用。如果我的 tableview 中有多个部分,我应该如何设置 forKey 值?
如何根据部分和行设置此值self.cache.setObject(image!, forKey:indexPath.row)?谢谢!!
这是我的UITableView 代码
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
if(tableView == tableview){
return categoryArray.count
}else{
return 1
}
}
func tableView(tableView : UITableView, titleForHeaderInSection section: Int)->String
{
if(tableView == tableview){
return categoryArray.objectAtIndex(section) as! String
}else{
return ""
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(tableView == tableview){
print("Count = \(myList[section].count)")
return myList[section].count
}
else{
return 5
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if(tableView == tableview) {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomEventCell
cell.cellBackgroundImg.image = UIImage(named: "placeholder")
if (self.cache.objectForKey(indexPath.row) != nil){
print("Cached image used, no need to download it")
cell.cellBackgroundImg?.image = self.cache.objectForKey(indexPath.row) as? UIImage
}else{
let img_url = myList[indexPath.section].objectAtIndex(indexPath.row).objectForKey("image") as? String
if img_url != nil{
print("Load the image from URL")
let url = NSURL(string: img_url!)!
let request = NSMutableURLRequest(URL:url)
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = defaultSession.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error: NSError?) in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let image = UIImage(data: data!)
cell.cellBackgroundImg?.image = image
self.cache.setObject(image!, forKey:indexPath.row)
})
})
task.resume()
}
}
return cell
}
}
【问题讨论】:
-
尝试使用
tag- (一个整数,可用于识别应用程序中的视图对象。)而不是indexPath.row -
@Rahul 抱歉,请您详细说明您的评论
-
为什么不使用 URL 字符串作为缓存的键?这样如果同一张图片多行、多节或者行数发生变化,缓存就会有效
-
为什么不使用 img_url 作为字典中图像的键。这样,您可以从 myList 获取 img_url,然后查看该 url 的缓存中是否存在图像。那么你就不用担心行和节了
-
@Paulw11 是的,谢谢你的想法。我将使用 URL 字符串。谢谢。
标签: ios swift uitableview caching