针对数组测试 TableView 的单元格中包含的值

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

我需要测试自定义单元格标签的值是否包含在数组中。为了实现这一点,我创建了一个函数来执行测试和 returns 一个布尔值。我的问题是每次单元格进入屏幕时,都会再次进行测试。 我应该在哪里进行测试以便只进行一次?

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
}

我需要能够修改单元格以响应此测试。感谢您的帮助!

每次单元格出现时都会调用您的测试,因为您将测试调用放在 cellForRowAtIndexPath: 中(如果像您说的那样,您需要根据测试结果更改单元格的标签值,我不会查看其他选择)

您可以尝试使用 UITableViewDelegate 方法

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

每次需要显示一个单元格时都会调用它。

第二种方法有点棘手,我不推荐它,您可以创建一个 pool(数组)UITableViewCells 并从该池中维护(调用测试和更改值)在您认为最好的时候(例如滚动 tableView 时)