Reputation: 612
Here is the really weird behavior. When the table view is first loaded, it looks like this:
Now, when I scroll down and then scroll back up, the buttons appear on cells that didn't have buttons on them before! Like so:
I know this has to do with "This is the intended behaviour of a UITableView. The whole point of a UITableView is to queue up cells that are needed and release cells that aren't needed to manage memory" as described in this post: UITableView in Swift: Offscreen cells are not pre-loaded.
Here is my code:
var messages = [String]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CathyTaskLogTableViewCell
if messages[indexPath.row] != "" {
cell.messageButton.hidden = false
}
return cell
}
Anybody have a solution to this problem?
Upvotes: 0
Views: 677
Reputation: 32809
There are two possible solutions to your problem:
Always set the hidden
property:
cell.messageButton.hidden = messages[indexPath.row] != ""
Reset the state of your cell when it is reused, this provides deterministic behaviour in the table view controller, without burdening the controller class with tasks that a cell should do. This can be done by overwriting prepareForReuse
in CathyTaskLogTableViewCell
.
func prepareForReuse() {
super.prepareForReuse()
self.messageButton.hidden = true // or false, depending on what's the initial state
// other stuff that needs reset
}
With the current code, messageButton
gets hidden only if the cell doesn't find something in messages
. So for cells that had this button visible, were reused, and now correspond to a cell that doesn't have a correspondent in messages
, the button will remain visible.
Upvotes: 0
Reputation: 3205
The reason for getting this result is because of UITableViewCell
is being reuse.
if messages[indexPath.row] != "" {
cell.messageButton.hidden = false
}
else
{
cell.messageButton.hidden = true
}
Upvotes: 1