Repeated cells while scrolling uitableview - ios

I am developing news feed and I am using uitableview to display data. I am loading each cell data synchronically in other thread and use protocol method to display loaded data:
func nodeLoaded(node: NSMutableDictionary) {
for var i = 0; i < nodesArray.count; ++i {
if ((nodesArray[i]["id"] as! Int) == (node["id"] as! Int)) {
nodesArray[i] = node
}
}
}
The problem is that when I scroll my uitableview (while data synchronically loading), some of my cells repeats (8 row has same content like first, or 6 row has the same content like second row). When I scroll after some time (I suppose after data is loaded) then all become normal.
I looking for answers and found that I have to check if cell is nill at cellForRowAtIndexPath, but in swift my code is different then in objective C:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: NewsCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsCell
var node = nodesArray[indexPath.row] as! NSDictionary
if (node["needLoad"] as! Bool) {
dbHelper.getNode(node["id"] as! Int, hash: node["id"] as! Int, tableName: DbHelper.newsTableName, callback: self)
} else {
cell.id = node["id"] as! Int
cell.titleLabel.text = node["title"] as? String
cell.descriptionLabel.text = node["description"] as? String
cell.imgView.image = WorkWithImage.loadImageFromSD((node["image"] as! String))
}
return cell
}
Also I can't check if cell == nil bcs of binary error (NewsCell can't be nil).
What should I do? Thx.

you seem to have created a separate class for UITableViewCell. The problem with your code is that you are not resetting the labels when reuse happens.
Oveeride prepareForReuse method in your custom UITableviewCell class and reset your interfaces there. That should fix the issue.

Related

Swift Button inside CustomCell (TableView) passing arguments to targetMethod

My TableView features custom Cells which have a button to display corresponding detailed info in another view.
This thread here got me started and I tried to implement the approach with the delegate inside the customCell:
How to access the content of a custom cell in swift using button tag?
What I want to achieve is that when I click on the button it reads the name of the cell and passes it on to the next controller. However it seems that I cannot pass the name with the delegate method and its field is nil.
How can I get the specific content of a cell when clicking on its button?
This is what I did so far:
In the class creating my own cell I set delegate:
protocol CustomCellDelegate {
func cellButtonTapped(cell: DemoCell)
}
(........)
var delegate: CustomCellDelegate?
#IBAction func buttonTapped(sender: AnyObject) {
delegate?.cellButtonTapped(self)
}
In the TableViewController I have the following:
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCellWithIdentifier("FoldingCell",
forIndexPath: indexPath) as! DemoCell
cell.delegate = self
//TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer
let resultList = self.items["result"] as! [[String: AnyObject]]
let itemForThisRow = resultList[indexPath.row]
cell.schoolNameClosedCell.text = itemForThisRow["name"] as! String
cell.schoolNameOpenedCell.text = itemForThisRow["name"] as! String
self.schoolIdHelperField = itemForThisRow["name"] as! String
cell.schoolIntroText.text = itemForThisRow["name"] as! String
//call method when button inside cell is tapped
cell.innerCellButton.addTarget(self, action: #selector(MainTableViewController.cellButtonTapped(_:)), forControlEvents: .TouchUpInside)
cell.school_id = itemForThisRow["name"] as! String
// cell.schoolIntroText.text = "We from xx University..."
return cell
}
And finally the target method when the button inside the cell is clicked
func cellButtonTapped(cell: DemoCell) {
print("the school id: ")
print(cell.schoolNameOpenedCell) //this line throws an error EXC_BAD_ACCESS 0x0
}
Firstly, the object innerCellButton is not a Cell, it's a button. The simple way to solve your problem is, just refer the index of the button. Please find the below method.
func cellButtonTapped(AnyObject: sender) {
let resultList = self.items["result"] as! [[String: AnyObject]]
//Get the tag value of the selected button.
//Button tag should be matching with the corresponding cell's indexpath.row
let selectedIndex = sender.tag
let itemForThisRow = resultList[selectedIndex]
print("the school id: \(itemForThisRow[\"name\"])")
}
* And set each button's tag as indexPath.row *
E.g.,
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue your cell and other code goes here.
// set the button's tag like below.
cell.innerCellButton.tag = indexPath.row
return cell
}
Close. I wouldn't use Suresh's method since it does not help find the IndexPath, which includes section and row.
First, I would recommend a model object for your table view data source. Learn more about the MVC pattern as well as parsing a JSON response to an object with mapping. However, this would give you the data you want.
func cellButtonTapped(cell: UITableViewCell) {
let indexPath = tableView.indexPathForCell(cell)
let resultList = self.items["result"] as! [[String: AnyObject]]
let itemForThisRow = resultList[indexPath.row]
let name = itemForThisRow["name"] as! String
}

Swift - Type Casting

I am building a custom UITableView with custom cells.
Each of the custom cells are a subclass of FormItemTableViewCell
I am attempting to populate the cell data in cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = FormItemTableViewCell();
if(indexPath.row == 1){
cell = tableView.dequeueReusableCellWithIdentifier(twoOptionCellIdentifier, forIndexPath: indexPath) as! TwoOptionTableViewCell
} else {
cell = tableView.dequeueReusableCellWithIdentifier(oneTextFieldCellIdentifier, forIndexPath: indexPath) as! OneTextFieldTableViewCell
}
cell.questionLabel.text = "What is the meaning of life?";
return cell
}
How do I access the elements in the subclass?
For example: TwoOptionTableViewCell has a segControl
while the OneTextFieldTableViewCell has a answerTextField
There are some decent answers in this question but most of them have one bad thing in common, they force unwrapped optionals, which you should avoid as much as you can (pretty much the only acceptable place to use them is in IBOutlets)
This is what I think is the best way to handle this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("Identifier", forIndexPath: indexPath) as? FormItemTableViewCell else {
fatalError("Cell is not of kind FormItemTableViewCell")
}
switch cell {
case let cell as TwoOptionTableViewCell where indexPath.row == 1:
// Configure cell, which is an object of class TwoOptionTableViewCell, but only when we are in row 1
break
case let cell as TwoOptionTableViewCell:
// Configure cell, which is an object of class TwoOptionTableViewCell, when the row is anything but 1
break
case let cell as OneTextFieldTableViewCell:
// Configure cell, which is an object of class OneTextFieldTableViewCell
break
case _: print("The cell \(cell) didn't match any patterns: \(indexPath)")
}
cell.questionLabel.text = "What is the meaning of life?";
return cell
}
Now let me walk you through the reasons I think it's the best way.
First of all, it doesn't force unwraps any optionals, everything is unwrapped nicely in the switch case.
It dequeues your cell from the table (something you should always do) and makes sure it's a subclass of FormItemTableViewCell, otherwise it throws a fatal error.
By using a switch case, it casts cell into the class you need, and at the same time it checks if it's the index path you want. So if you want to share some logic in different rows that share a class, you can compare indexPath.row to multiple values. If you don't use the where clause, it will use the same logic in all places where it finds a cell with that class.
Do note that you will need to add some logic to get the desired identifier depending on the row.
You can use one of the two approaches:
1) The best way:
if(indexPath.row == 1) {
let cell = tableView.dequeueReusableCellWithIdentifier(twoOptionCellIdentifier, forIndexPath: indexPath) as! TwoOptionTableViewCell
// the type of cell is TwoOptionTableViewCell. Configure it here.
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(oneTextFieldCellIdentifier, forIndexPath: indexPath) as! OneTextFieldTableViewCell
// the type of cell is TwoOptionTableViewCell. Configure it here.
return cell
}
2) If you declare cell just once, as a superclass, then you have to downcast it like this.
var cell: FormItemTableViewCell
cell = ... // dequeue and assign the cell like you do in your code.
if let twoOptionCell = cell as? TwoOptionTableViewCell
{
// configure twoOptionCell
}
else if let oneTextFieldCell = cell as? OneTextFieldTableViewCell
{
// configure oneTextFieldCell
}
return cell
This is more verbose, once you add the code to dequeue the cell. So I personally prefer and recommend the first approach.
If I understand correctly, you want to keep main declaration of cell as FormItemTableViewCell to access common properties.
You can create a new variable and assign it the casted version.
Do your stuff with this instance as this is a class object it will point to same reference.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = FormItemTableViewCell();
// this can be replaced with below line as I don't see the purpose of creating an instance here while you use dequeue below.
// var cell: FormItemTableViewCell!
if(indexPath.row == 1){
cell = tableView.dequeueReusableCellWithIdentifier(twoOptionCellIdentifier, forIndexPath: indexPath);
let tempCell = cell as! TwoOptionTableViewCell;
// access members of TwoOptionTableViewCell on tempCell
tempCell.segControl.someProperty = 0;
} else {
cell = tableView.dequeueReusableCellWithIdentifier(oneTextFieldCellIdentifier, forIndexPath: indexPath);
let tempCell = cell as! OneTextFieldTableViewCell;
// access members of OneTextFieldTableViewCell on tempCell
tempCell.answerTextField.text = "42";
}
cell.questionLabel.text = "What is the meaning of life?";
return cell
}
You're going to have to conditionally cast them in that case. I like using Enums for Rows/Sections instead of == 1 (depending on how your TableView is setup), but basically you'll want to do the following:
if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier(twoOptionCellIdentifier, forIndexPath: indexPath) as! TwoOptionTableViewCell
// Note that we cast the cell to TwoOptionTableViewCell
// access `segControl` here
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(oneTextFieldCellIdentifier, forIndexPath: indexPath) as! OneTextFieldTableViewCell
// This cell we cast to OneTextFieldTableViewCell.
// access `answerTextField` here
return cell
}
What you were doing was defining the cell as FormItemTableViewCell, so subsequent accesses would only know it in that form even though you explicitly cast it to a subclass during assignment.
As a side-note, you don't have to assign to the var as you did there, what you could do is let cell: FormItemTableViewCell. Then in the if-statements you could define new cells of the subclasses, operate on them, and then assign back to your original cell and then return that. This is useful if you're going to be performing the same operations on both cell types after the if statements (such as setting a background colour or something, regardless of which subclass you have).
Here is my favourite way of handling this situation:
enum CellTypes {
case TwoOption, OneTextField
init(row: Int) {
if row == 1 {
self = .TwoOption
} else {
self = .OneTextField
}
}
var reuseIdentifier: String {
switch self {
case .TwoOption: return "twoOptionReuseIdentifier"
case .OneTextField: return "oneTextFieldReuseIdentifier"
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: FormItemTableViewCell
let cellType = CellTypes(row: indexPath.row)
switch cellType {
case .TwoOption:
let twoOptionCell = tableView.dequeueReusableCellWithIdentifier(cellType.reuseIdentifier, forIndexPath: indexPath) as! TwoOptionTableViewCell
// do stuff with the `segControl`
cell = twoOptionCell
case .OneTextField:
let textFieldCell = tableView.dequeueReusableCellWithIdentifier(cellType.reuseIdentifier, forIndexPath: indexPath) as! OneTextFieldTableViewCell
// do stuff with the `answerTextField`
cell = textFieldCell
}
// Here do something regardless of which CellType it is:
cell.questionLabel.text = "What is the meaning of life?"
return cell
}

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
}

Cells in table view not being displayed

I am using a UITableView in one of my view controllers and am using a custom class called ListCell. The table view and the cells are being displayed, but the content in the cells are not being displayed, so the cell is empty. But if I press the cell it performs its task. So the content is there but its not being displayed. I think it has something to do with how I registered the class to the custom type ListCell. Here is how I declared it in viewDidLoad...
self.tblListView.registerClass(ListCell.self, forCellReuseIdentifier: "Cell")
Is there something wrong with the above line. And what it is causing the cell content to not being displayed?
Also I tried enabling size classes and that did not work. Also all the cells are being created programmatically.
The below line of code is responsible for displaying the cell data.
cell.displayAlertData(mutArrAlertList.objectAtIndex(indexPath.row) as! [NSObject : AnyObject])
the thing is mutArrAlertList's object at the first index is an optional type Optional(Temperature). I think the only way this will work if it is not optional. The object is being passed my a push notification, and what the push notification sends is not optional. So somewhere it randomly turns into an optional type. Is there a way I can get rid of that optional value around it?
Here is cell for row method:
func tableView (tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier: String = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ListCell
//if cell == nil
//{
//let nib: NSArray = NSBundle.mainBundle().loadNibNamed("ListCell", owner: self, options: nil)
//cell = (nib.objectAtIndex(0) as? ListCell)!
//}
cell.selectionStyle = UITableViewCellSelectionStyle.None
print("")
print("This is cell: \(mutArrAlertList.objectAtIndex(indexPath.row) as! [NSObject : AnyObject])") //did this to check what the value is and it is an optional
cell.displayAlertData(mutArrAlertList.objectAtIndex(indexPath.row) as! [NSObject : AnyObject])
if indexPath.row == mutArrAlertList.count-1
{
if ApplicationDelegate.intPage > mutArrAlertList.count
{
//do nothing
}
else
{
ApplicationDelegate.intPage = ApplicationDelegate.intPage + 10
self.reloadDataFromdb()
}
}
return cell
}

UITableView smooth scrolling

I have UITableView with images in each cell and I want my scrolling be smooth. So I read some post on stackerflow and now I am loading my images in background thread:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
var node = nodesArray[indexPath.row] as! NSMutableDictionary
if !checkIfImagesLoaded(node[Api.pictures] as! NSMutableArray) {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
cell.indicator.hidesWhenStopped = true
cell.indicator.startAnimating()
dbHelper.getBuildingStatusNode(node, callback: self)
} else {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
var image = WorkWithImage.loadImageFromSD((node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)! // Bad
dispatch_async(dispatch_get_main_queue()) {
cell.imgView.image = image
cell.indicator.stopAnimating()
}
}
}
return cell
}
dbHelper.getBuildingStatusNode(node, callback: self) method executes in background thread also. But for some reasons when I scroll I still get some delay. I read that it is good to fill my cell with data in tableView:willDisplayCell method instead tableView:cellForRowAtIndexPath and I should return cell as faster as I can in tableView:cellForRowAtIndexPath method. The question is should I now use the code like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
var node = nodesArray[indexPath.row] as! NSMutableDictionary
if !checkIfImagesLoaded(node[Api.pictures] as! NSMutableArray) {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
cell.indicator.hidesWhenStopped = true
cell.indicator.startAnimating()
dbHelper.getBuildingStatusNode(node, callback: self)
} else {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
var image = WorkWithImage.loadImageFromSD((node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)!
dispatch_async(dispatch_get_main_queue()) {
cell.imgView.image = image
cell.indicator.stopAnimating()
}
}
}
}
And what else I can do to make my scrolling more smooth? BCS I still have lags even when I use willDisplayCell method.
P.S. Image size in my UITableViewCells is fixed.
Try the following
Try removing any shadows.
Make the cell and its subviews opaque. Don't use alpha/transparency.
Try decoding the images on a background thread :
Decode images in background thread?
First of all it is better to subclass UITableViewCell and just pass your Api object to cell and make this mapping inside cell.
Also it is better to use some library like: AFNetworking's extension or AsyncImageView - it is possible to use in Swift.
Try to remove any border rounding, shadow, transparencies - they can cause delays. In this case you need rasterization:
Related question:
Sluggish scrolling experience when using QuartzCore to round corners on UIImageView's within a UITableViewCell
When you load image from URL it takes time to download image and that cause block in scrolling UITableView.
You are doing so much work simply do
Use this class SDWebImage
and in your bridging header file :
#import "UIImageView+WebCache.h"
Here is a code example that should work :
let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType!, imageURL: NSURL!) -> Void in
println(self)
}
let url = NSURL(string: node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)
cell.imgView.sd_setImageWithURL(url, completed: block)

Resources