[英]UITableView freezing during scroll in swift
我有這個問題大約3-4周。 我用谷歌搜索,檢查了一切,但仍然沒有工作。 請幫我!
在每個移動的滾動cellForRowAtIndexPath
重新加載tableView
,它開始凍結。
我對cellForRowAtIndexPath
函數的tableview是這樣的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as! MoviesTVC
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
let dictionary = self.rows[indexPath.row] as? [String: AnyObject]
dispatch_async(dispatch_get_main_queue(),{
cell.setCell(dictionary!)
})
})
return cell
}
setCell()
函數:
func setCell(dictionary: AnyObject){
let ImgString = dictionary["src"] as? String;
let ImgUrl = NSURL(string: ImgString!);
let ImgData = NSData(contentsOfURL: ImgUrl!)
self.movImg.image = UIImage(data: ImgData!);
self.movName.text = dictionary["name"] as? String;
self.movComment.text = dictionary["caption"] as? String;
}
您在后台異步任務中有錯誤的代碼。 目前,您只是在后台從陣列中獲取值,這是一個非常快速的過程......
你應該做的是在后台運行困難的任務,然后在前台更新UI。
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as! MoviesTVC
let dictionary = self.rows[indexPath.row] as? [String: AnyObject]
cell.setCell(dictionary!)
return cell
func setCell(dictionary: AnyObject){
let ImgString = dictionary["src"] as? String;
let ImgUrl = NSURL(string: ImgString!);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
let ImgData = NSData(contentsOfURL: ImgUrl!)
let image = UIImage(data: ImgData!);
//Possibly resize the image here in the background task
//so that the cpu doesn't need to scale it in the UI thread
dispatch_async(dispatch_get_main_queue(),{
self.movImg.image = image
})
})
self.movName.text = dictionary["name"] as? String;
self.movComment.text = dictionary["caption"] as? String;
}
編輯:在評論中回答您的問題。 最簡單的解決方案是為每個“image”單元格的字典添加一個屬性。 然后,當您加載單元格時,如果字典的“image”屬性存在,那么您只需將該圖像加載到單元格中即可。 如果它不存在,則下載並將其保存到字典中,然后將其添加到您的單元格。
更難的解決方案是將圖像下載到本地資源位置。 然后使用imageNamed
從文件加載圖像。 這將為您處理緩存和內存釋放。 那將是更好的選擇。
更好的是使用CoreData。 在任何這些解決方案中,您都必須在運行不足時管理清除文件存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.