Table view with images stutters while scrolling - ios

I have a table view which loads custom table view cells. In the table view cell I have an image view, among other controls. The problem is that the table view stutters while scrolling, even though the images are being read from Cache or documents directory (using either isn't making any difference)
Here is the code for displaying the table view cell:
func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
if cell.isKindOfClass(EventsTableViewCell) {
let eventCell = cell as! EventsTableViewCell
let list = self.eventsList
if list.count > 0 {
let event = list.objectAtIndex(indexPath.row) as! Event
//other cell labels configured here
//imageCache is NSCache instance
if let imageData = self.imageCache.objectForKey(event.name) as? NSData {
let image = UIImage(data: imageData)
eventCell.eventImageView.image = image
}
else if event.imageUrl != "" {
eventCell.setImageToCell(event)
}
}
}
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "eventCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
if cell == nil {
let nibCollection = NSBundle.mainBundle().loadNibNamed("EventsTableViewCell",
owner: nil,
options: nil)
cell = (nibCollection as NSArray).objectAtIndex(0) as? EventsTableViewCell
}
cell?.selectionStyle = .None
return cell!
}
In EventsTableViewCell,
func setImageToCell(event: Event) {
//apply placeholder image. This image will be replaced if an image is found for the particular event.
if event.image != nil {
dispatch_async(dispatch_get_main_queue(), {
self.eventImageView.image = event.image
})
}
}
So even though none of the images are being downloaded here, the table view still can't handle the scrolling properly. I am not sure what I am doing wrong. Can the size of the images be an issue here?

Related

how can I get the image from dynamically generated UITableViewCell and pass it with segue to the other View?

I have a UITableViewController with UITableViewCell dynamically generated there. Each cell contains an imageView that I'm filling with images fetched from my server. I'm using alamofire_images to do so. My code looks as follows:
func tableView(testDetailsPanel: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell
let test:SingleTest = self.items[indexPath.row] as! SingleTest
if(test.photo != "") {
cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!)
} else {
cell.myPhoto.image = UIImage(named: "clusterLarge")
}
return cell
}
I thought that since I'm downloading images while displaying the table, there is no need to download it again on the other screen (which is accessible through clicking each cell).
So my idea was to pass the image from specific cell to the other screen through segue. But the problem is that from the method prepareForSegue I don't have access to the specific cell that user clicks. So my other choice was to use protocols. I created a very simple one:
protocol HandlePhoto: class {
func setUpBackgroundPhoto(miniature: UIImage)
}
and then in my native class I wanted to use it in didSelectRowAtIndexPath method:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let test:SingleTest = self.items[indexPath.row] as! SingleTest
let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell
if(test.photo != "") {
handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!)
self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test)
}
} else {
self.performSegueWithIdentifier("testTextDetailsSegue", sender: test)
}
}
But this line:
handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!)
throws error:
fatal error: unexpectedly found nil while unwrapping an Optional value
So my final question is: how can I access photo from the specific cell that user chooses and pass it to other view (without downloading it there for the 2nd time)?
Your didSelectRowAtIndexPath implementation is wrong, with dequeueReusableCellWithIdentifier you are obtaining a new cell, not the selected cell.
Try this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let selectedCell = tableView.cellForRow(at: indexPath) as! TestDetailsCell
//this will return downloaded image or "clusterLarge"
let image = selectedCell.myPhoto.image
//
//Make your check on image and extra setup
//
self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test)
}
Why are you using dequeueReusableCellWithIdentifier in your didSelectRowAtIndexPath?; instead, you should get the cell directly using:
let cell = yourTableView.cellForRowAtIndexPath(indexPath) as! TestDetailsCell
if let image = cell.testPhoto.image {
print(image)//this is what you want.
}

First cell wrong size

I need to get the first cell in my tableView to be a different size from the rest. The rest of my cells are all under the class CustomPFTableViewCell, but the first one is a different cell so its under the class FirstPFTableViewCell, both of which extend from the class PFTableViewCell. Right now, I just used an if depending on the indexPath.row for whether or not the cell was the first cell. When its not it will load data for the cell from Parse.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
if(indexPath.row >= 1){
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomPFTableViewCell!
print("Loading Parse Database Files...")
// Extract values from the PFObject to display in the table cell
if let name = object?["Name"] as? String {
cell?.nameTextLabel?.text = name
print("Loading " + name)
}
if let author = object?["authorName"] as? String {
cell?.authorTextLabel?.text = author
}
if let likes = object?["Likes"] as? Int {
let stringVal = String(likes)
cell?.numLikes.text = stringVal
}
if let descrip = object?["Description"] as? String {
cell?.descriptionHolder = descrip
}
let initialThumbnail = UIImage(named: "Unloaded")
cell.customFlag.image = initialThumbnail
if let thumbnail = object?["imageCover"] as? PFFile {
cell.customFlag.file = thumbnail
cell.customFlag.loadInBackground()
}
return cell
}
print("Finished loading!")
let cell = tableView.dequeueReusableCellWithIdentifier("firstCell") as! PFTableViewCell
return cell
}
The end is empty because I'm not sure how to go about changing the one/first cell's size. (In the Interface Builder its set to 60). I guess the most important part in solving this is this:
let cell = tableView.dequeueReusableCellWithIdentifier("firstCell") as! PFTableViewCell
return cell
}
In order to play with the size of the cell you have to implement the UITableViewDelegate function
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return firstCellHeight
} else {
return customCellHeight
}

Cell not being displayed - "no index path for table cell being reused"

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("Wall Delegate: caso 2")
let cell = tableView.dequeueReusableCellWithIdentifier("you1on1Cell", forIndexPath: indexPath) as! OneToOneCell
let cell1 = tableView.dequeueReusableCellWithIdentifier("other1on1Cell", forIndexPath: indexPath) as! OneToOneCell
let newMessage = messages[indexPath.row]
if(newMessage.you == true){
if let picture = imageYou { cell.profilePictureyou.image = picture }
if let textmsg = newMessage.text {
cell.messageTextYou.text = textmsg
}
return cell
} else {
if let picture = imageOther { cell1.profilePicture.image = picture }
if let textmsg = newMessage.text { cell1.messageText.text = textmsg }
return cell1
}
I don't know what is the problem, this error is being showed up, however app is still running, but text is only displayed when I click on tableview with mouse on simulator - it is the first app I am developing and it is the first time I am using a table view with two different cell structure (however it is the same cell file). This is meant to be a chat.

Tableview reusing the cells and showing wrong data first

Hello I’ve been having this problem for awhile. I want to stop the tableview from reusing the cell. It keeps displaying the wrong information when i scroll then it shows the right thing like a few milliseconds. How can i stop the tableview from reusing the cell or how can i reuse the cell and make it not do that.
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cats.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CategoryTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CategoryTableViewCell
cell.nameLabel.text = cats[indexPath.row].categoryName
cell.subNameLabel.text = cats[indexPath.row].appShortDesc
let catImageUrl = cats[indexPath.row].imageUrl
let url = NSURL(string: "https:\(catImageUrl)")
let urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error != nil {
print(error)
} else {
if let ass = UIImage(data: data!) {
cell.photoImageView.image = ass
}
self.loading.stopAnimating()
}
}
return cell
}
The problem is that you are seeing an image from a previous cell. Simply initialize the image to nil when you dequeue the reused cell:
cell.photoImageView.image = nil
or set it to a default image of your choosing.
Note, the way you are updating the image after it loads has issues.
The row may no longer be on screen when the image finally loads, so you will be updating a cell that has been reused itself.
The update should be done on the main thread.
A better way to do this would be to have an array that caches the images for the cells. Load the image into the array, and then tell the tableView to reload that row.
Something like this:
dispatch_async(dispatch_get_main_queue()) {
self.imageCache[row] = ass
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: 0)],
withRowAnimation: .None)
}
override prepareForReuse() method in your cell class and reset your values
override func prepareForReuse() {
super.prepareForReuse()
nameLabel.text = ""
}
This method is called every time the UITableView before reuses this cell

Repeating images when scrolling in UITableView Swift

EDITED CODE FROM BELOW ANSWER
WHAT I WANT
The images are correct size and show in the correct positions
WHAT I GET
A bunch of images showing up everywhere randomly when I scroll
I have looked through so many answers and I still haven't found a solution to my problem. It seems quite often it is a different problem for each person, and it doesn't help that most questions here are in Objective-C. I find it difficult converting from one to another.
I will just show my table view functions and explain my code and maybe somebody can identify the problem or help me to identify to solve it myself.
-----------------------------------------------------------------------------------
Explanation
Not all News Items (cells) contain pictures. So as you can see (in the first function below) I loop through the sections and the nested cells and if the news item contains a picture if newslists[i][j] != "None, I display the image. From this point it is familiar code, seen from the tutorial here
In the second function I once again loop through the sections and the cells till I land on one that should contain an image. I then change the height of this cell so the image will fit inside.
That is pretty much it...
any ideas?
-----------------------------------------------------------------------------------
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
}
I have one more function that may be causing problems but I doubt it:
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
}
I'm not sure why you have a double for loop in both method. There are called for every indexPath possible so you can just get you appropriate data with the indexPath section and row.
You can try this code, i don't see any reason for it to not work.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! UITableViewCell
cell.imageView?.image = nil
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 {
...
}
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if newslists[indexPath.section][indexPath.row].imageURL != "None"{
println("Expanding cell for \(i) \(j)")
return 190.0
}
return 70.0
}
All we need to do is use the prepareForReuse() function. As discussed in this medium article, This function is called before cell reuse, letting you cancel current requests and perform a reset.
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}

Resources