UITableView Cell Reuse & Old Data - ios

I would like to confirm the approach I took to solve an issue with dequeuing custom cells in a UITableView as it scrolls such that the cells do not contain the old cell's data...
The app that contains a UITableView with custom UITableViewCells ("CustomCell"). Each CustomCell contains a UIStackView with one or more custom views via a nib ("CustomView"). I reuse the CustomCell as follows:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifierCustomCell, forIndexPath: indexPath) as! CustomCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
The issue was that the cell would contain "old" data as the cell was being reused. To fix this, I override the prepareForReuse method in CustomCell as follows:
override func prepareForReuse() {
super.prepareForReuse()
for case let view as CustomView in stackView.subviews {
view.removeFromSuperview()
}
}
Then in layoutSubviews, I add the subviews back in:
override func layoutSubviews() {
super.layoutSubviews()
if stackView.subviews.isEmpty {
addCustomViewsToCell()
}
}
Performance seems fine thus far, but curious if this is a proper approach or if I will run into issues with scale in the future. I have not been able to find another workable approach thus far.
Thanks

Your code to reuse cells is correct. A common approach is to configure your cell's data within the cellForRowAtIndexPath function by setting a variable or calling a function on your custom cell:
let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifierCustomCell, forIndexPath: indexPath) as! CustomCell
cell.data = myData[indexPath.row] // where myData is an array of type [Data]
return cell
Your cell would be in charge of its own layout to display the new data:
var data: Data {
didSet {
// configure and refresh your UI here
}
}
I suspect your issue has to do with your configureCell function. If you can, move this code into your cell's logic instead. This will be cleaner and easier to understand.
As far as performance, you might be fine now if your stack views don't have much content in them, but if they continue to grow in complexity you might see frame rate drops on older devices.

Related

How to reload a collectionview cell without reloading an image

I have a collection view and when something changes I update the data source and reload the cell in which the change occurs. The cell kind of blinks when it reloads. It doesn't really affect the user scrolling and I made it almost unnoticeable with:
UIView.performWithoutAnimation{
self.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}
This was the best I could do to make the reload less noticeable. I have a background image taking up the entire cell. I think the flash that I'm seeing is this image reloading, yet I don't need it to reload because the image will never change. Does anyone know how to make the cell reload but not the image? I can put a variable in there and change it such as (initalLoad = false) but I don't know how to keep the image from reloading.
Try moving all your cell setup to an internal func in your UICollectionViewCell subclass:
class MyCollectionViewCell: UICollectionViewCell {
var initialLoad = true
// since collection view cells are recycled for memory efficiency,
// you'll have to reset the initialLoad variable before a cell is reused
override func prepareForReuse() {
initialLoad = true
}
internal func configureCell() {
if initialLoad {
// set your image here
}
initialLoad = false
// do everything else here
}
}
and then calling it from your view controller:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
cell.configureCell()
return cell
}
You can add parameters to the configureCell() function to pass in any data you need for setting up the cell (presumably you'll need to pass in some kind of reference to your image). If you have a lot of information, you might want to create a custom object to hold all that information, then pass that into the function as a parameter.

Comment controller with table view section header and footer

How can I achieve this screen with UITableViewCell and UITableViewController. With table section and header. Some ideas to achieve this?? Thanks!
What have you tried so far?
Your question seems a little broad.
You will need a set of custom UITableViewCell Subclasses, which you design in nibs.
To make the cells seem apart from each other, resize the content size of the Cells, and make the cell background another color.
Create a Segmented Control and add it to the Tableviews HeaderView.
For the FooterView it seems like this is some kind of subclassed Tabbar.
Easiest way to customise it in such a way, would be to create a View, and add buttons to it. Add this View as Subview to your TableViewController.
Have 2 UITableViewCell's one for each type i.e. 1 for showing the image and text and another for showing just the text.
Then in the cellForRowAt delegate method determine which to type to use based off the object you are data binding it to.
Example:
public final func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customObject = customObjects[indexPath.section]
switch customObject.type {
case .imageAndText:
if let cell = tableView.dequeueReusableCell(withIdentifier: ImageAndTextCell.identifier, for: indexPath) as? ImageAndTextCell {
cell.customObject = customObject
return cell
}
case .text:
if let cell = tableView.dequeueReusableCell(withIdentifier: TextCell.identifier, for: indexPath) as? TextCell {
cell.customObject = customObject
return cell
}
}
return UITableViewCell()
}

Calling super.tableView(tableView: UITableView, cellForRowAtIndexPath... with reuseIdentifier

First, I wanted to point out the reason I want to make a common call, when a reusable cell is dequeued in a base class, it's because of this line of code you will see again soon further in my question:
cell.backgroundColor = cell.contentView.backgroundColor;
This is a bug fix for iPad not respecting the UITableView.backgroundColor = myCustomColor and UITableViewCell.backgroundColor = clearColor I have set. iPad displays white instead, everything is fine in iPhone versions, you can see this bug here, I have to set the background color again each time the cell is dequeued that is the only solution that works for me. I am trying to do this once in my base class, and come up with a solution where I do not have to remember to call a func for every child class (might not be possible).
I have a couple custom UITableViewControllers classes, let's call them ATableViewController and BTableViewController they inherit from a base class called UIBaseDashboardTableViewController which inherits from UITableViewController.
I am generating dynamic Prototype Table cells and making use of the function below in ATableViewController and BTableViewController:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ATableViewCellId", forIndexPath: indexPath)
//common setting to fix always white background in iPad bug
cell.backgroundColor = cell.contentView.backgroundColor;
return cell
}
The TableViewCell Id ACustomTableCellId is unique or different for ATableViewController and BTableViewController. I have a common setting for all my UITableViewControllers that inherit from my base class, UIBaseDashboardTableViewController. You can see the backgroundColor line of code above is my common setting that will be the same in all child classes of UIBaseDashboardTableViewController. In each child class I first tried to do the following:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
super.tableView(tableView: tableView, cellForRowAtIndexPath: indexPath)
...
}
But that is not going to work, I need the ReusableCellIndentifer.
My current solution, which really is just fine probably, is the following, in my child classes I have the following:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let data = dataArray[indexPath.row]
let dequeuedCell = tableView.dequeueReusableCellWithIdentifier("BTableViewCellID", forIndexPath: indexPath)
let cell = dequeuedCell as! MyCustomTableViewCell
// Configure the cell...
cell.model = data
//call common settings for cells function in base class
super.setDequeueReusableCellCommon(cell)
return cell
}
And then in my base class UIBaseDashboardTableViewController I implemented:
func setDequeueReusableCellCommon(cell: UITableViewCell) {
cell.backgroundColor = cell.contentView.backgroundColor
}
The only downside to this is that I have to remember to call super.v setDequeueReusableCellCommon in all my child classes.
Any better suggestions on how solve this?
You are changing background color for cell, but made inheritance for tableViews. Use inheritance for tableViewCell, not the whole tableView. And in root class for tableViewCell setup self.backgroundColor = self.contentView.backgroundColor in awakeFromNib method.

How to update self-sizing tableview's height?

If I put a custom view in a cell , how can I notify tableview to update cell's height if my custom view's height has changed? I tried invalidateIntrinsicContentSize but that doesn't work. ReloadData works but I doubt whether using
self.superview?.superview?.superview as! UITableView).reloadData()
is a good implementation.
I have seen a similar question here but that's all about view from standard library. And this and this have no answer.
You are thinking in the right direction. However there are two problems with your approach:
reloadData reloads the whole table view and it does not animate the change.
Moving up the superview chain is bound to break when Apple changes the UITableView view hierarchy. They have done that before, so they might do it again.
To fix the first issue you should call reloadRowsAtIndexPaths:withRowAnimation: instead. That only reloads the cells that you specify in the indexPath array. So you pass it an array that only contains the indexPath of your cell.
The second issue is a bit trickier because a UITableViewCell has no reference to its UITableView (and it shouldn't). So it cannot tell the UITableView directly to reload the cell.
You can give each cell a closure that it should execute whenever its height has changed. So you just add a closure property in your custom cell:
class YourCustomTableViewCell: UITableViewCell {
var resizeClosure: (() -> Void)?
...
And you set this closure in your UITableViewControllerDataSource when you dequeue the cell:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("YourCustomCellIdentifier", forIndexPath: indexPath)
if let customCell = cell as? YourCustomTableViewCell {
customCell.resizeClosure = { [weak cell, weak tableView] in
if let currentIndexPath = tableView?.indexPathForCell(cell!) {
tableView?.reloadRowsAtIndexPaths([currentIndexPath], withRowAnimation: .Automatic)
}
}
}
return cell
}
Just make sure that you add tableView to the closure's capture list to avoid a strong reference cycle. That is done by adding the [weak tableView] to the closure.
And then when the cell changes its height you just execute the closure and the cell will be reloaded:
func someFunctionThatChangesTheHeight() {
// change the height
resizeClosure?()
}

UITableView with transparent cells overlap old cells when reloading data

I have a UITableView with a transparent background color and cells which also have a transparent background color. When I reload my tableView with:
dataSource = some new data
tableView.reloadData()
I can see the new cells overlap the old ones.
I did try to use use
tableView.beginUpdates()
// remove all rows here
change data source
// insert new rows here
tableView.endUpdates()
but it did not work. I tried as well tableView.reloadRowsAtIndexPath(...) but still no luck.
And finally I set all my cells and my table view to clear graphic context when redrawn but it did not manage to fix this issue.
Any help would be greatly appreciated.
My cell creation function:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("suggestioncell")
cell.backgroundColor = UIColor.whiteColor().alpha(0.1)
cell.textLabel?.text = (suggestions![indexPath.row] as! SVPlacemark).formattedAddress
cell.clearsContextBeforeDrawing = true
cell.contentView.clearsContextBeforeDrawing = true
return cell
}
Try overriding prepareForReuse in you UITableViewCell subclass, and reset content there.
Here's what the documentation says about that:
Prepares a reusable cell for reuse by the table view's delegate.
If a UITableViewCell object is reusable—that is, it has a reuse identifier—this method is invoked just before the object is returned from the UITableView method dequeueReusableCellWithIdentifier:. For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell. If the cell object does not have an associated reuse identifier, this method is not called. If you override this method, you must be sure to invoke the superclass implementation.
Custom UITableViewCell class:
class customCell: UITableViewCell {
override func prepareForReuse() {
self.textLabel?.text = nil
}
}
In your cellForRowAtIndexPath method:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("suggestionCell", forIndexPath: indexPath) as! customCell
cell.backgroundColor = UIColor.whiteColor().alpha(0.1)
cell.textLabel?.text = (suggestions![indexPath.row] as! SVPlacemark).formattedAddress
return cell
}
And, of course in your XIB/Storyboard, set the cell class to CustomCell, and set its reuse identifier.

Resources