我正在使用Swift 2
,我在UITableView
滚动时面临问题。
我的UITableView
有大量的单元格/记录,当我滚动tableview
时,内存会随着单元格一次又一次地创建而增加,内存警告会在didReceiveMemoryWarning()
中发生并且崩溃!!!
在Objc中,我们可以在cellForRowAtIndexPath
中实现单元格创建
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
// Create cell
}
但我如何在Swift 2
中管理此问题?如何优化我的UITableView
以便在图像加载的情况下滚动大量单元格。
我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let node = dataSource[indexPath.row]
if let theLabel = self.viewWithTag(1009) as? UILabel {
theLabel.text = node.TEXT
}
// More setting labels and image as well
return cell!
}
编辑1:
实际上我还添加了一个具有图像处理的子视图,
if let view = self.viewWithTag(1008) as? UIView {
let controller = self.getViewControllerWithIdentifier("MY_SUBVIEW") as! MY_SUBVIEW
controller.arraySource = node
self.containerAddChildViewController(controller, withRootView: view!)
}
子视图类是:
import UIKit
class MY_SUBVIEW: UIViewController {
var arraySource: NSArray?
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
func loadData() {
if let theLabel = self.viewWithTag(1007) as? UILabel {
theLabel.text = arraySource[0]["label"]
}
if let imageView = self.viewWithTag(1006) as? UIImageView {
guard let photo = arraySource[0]["photo"]
else {
imageView.image = nil
self.view.viewWithTag(1005).hidden = false
return }
let url = photo
self.setImageFrom(link: url)
self.view.viewWithTag(1005).hidden = true
}
}
func setImageFrom(link link:String) {
NSURLSession.sharedSession().dataTaskWithURL( NSURL(string:link)!, completionHandler: {
(data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if let data = data {
UIView.transitionWithView(self,
duration:0.5,
options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { self.image = UIImage(data: data) },
completion: nil)
}
}
}).resume()
}
}