Simon
Simon

Reputation: 137

Test a value contained in the cell of a TableView against an array

I need to test if the value of a custom cell label is contained within an array. To achieve this I created a function that does the test and returns a boolean. My problem is that every time the cell enters the screen, the test is done again. Where should I make the test so it is done only once ?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell
    var name:String = Array(self.contactList[indexPath.row].keys)[0]
    var phones:String = self.contactList[indexPath.row]["\(name)"]!
    cell.nameLabel.text = name
    cell.phoneLabel.text = phones
    cell.inviteButton.tag = indexPath.row

    var (matched, id) = self.isRegistered(phones)
    if(matched){
        cell.phoneLabel.text = "TRUE"
        cell.idUser = "\(id)"
    }

    return cell
}

I need to be able to modify the cell in response to this test. Thanks for your help !

Upvotes: 0

Views: 464

Answers (1)

YYfim
YYfim

Reputation: 1412

Your test is called every time the cell appears because you a placed the test call inside cellForRowAtIndexPath: (If like you said you need to change the cell's label value according to the test result, I don't see any other choice)

You can try using the UITableViewDelegate methods

optional func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)

This will be called every time a cell needs to be presented.

Second way is a bit tricky and I don't recommend it, you can create a pool (array) of UITableViewCells and maintain (call test & change values) from that pool at a time you think is best (when scrolling the tableView for example)

Upvotes: 1

Related Questions