I have created a UITableView to display a feed of particular photos from Instagram. I made a custom tableViewCell to display the image and the header contains the username. Everything displays correctly but when I scroll it lags quite heavily. I have read other posts about heightForRowAtIndexPath instead of setting the tableView.rowHeight and have done that correctly, which has reduced a bit of the lag.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Screen Width & Height
let screenSize: CGRect = UIScreen.mainScreen().bounds; let screenWidth = screenSize.width;
let screenHeight = screenSize.height;
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("feedCell") as UITableViewCell
let url = NSURL(string: mediaArray[indexPath.section])
let data = NSData(contentsOfURL: url!)
var cellImageName = UIImage(data: data!)
var cellImage = cellImageName
var cellImageView = UIImageView(image: cellImage)
cellImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth)
cell.addSubview(cellImageView)
//cell.imageView?.image = UIImage(data: data!)
return cell
}
Does anyone know how to fix the problem? Thanks
Edit: I have let data = NSData(contentsOfURL: url!)
downloading on a background thread and the rest on the main thread.
let url = NSURL(string: mediaArray[indexPath.section])
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {
//IMAGE
let data = NSData(contentsOfURL: url!)
var cellImage = UIImage(data: data!)
var cellImageView = UIImageView(image: nil)
dispatch_async(dispatch_get_main_queue()) {
if (cell.viewWithTag(1) == nil) {
cellImageView.tag = 1
var cellImage = UIImage(data: data!)
var cellImageView = UIImageView(image: cellImage)
cellImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth)
cell.addSubview(cellImageView)
}
}
I still have a problem where the feed re-uses the same cell. Any ideas?