如何设置UITableViewCell的风格与众不同?

时间:2017-08-28 14:34:58

标签: ios swift uitableview

我试图在TableView中为我的活动对象设置不同的样式。我尝试为我的对象设置一个标志(myObject.isActive)并在我的自定义UITableViewCell中读取它;

var myArray = [MyObject]()

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as? myCustomCell {
        if myArray.count > 0 {
            // Return the cell
            let myObject = myArray[indexPath.row]
            cell.updateUI(myObject: myObject)

            return cell
        }
    }

    return UITableViewCell()
}

myCustomCell:

func updateUI(myObject: MyObject){
    if myObject.isActive { 
        self.selectedCell()
    }
}

func selectedCell() {
    labelTitle.font = UIFont(name: "Montserrat-Medium", size: 32)
    labelTitle.textColor = UIColor(hex: 0x64BA00)
}

当tableView数据加载时,这很有用。但是当我滚动tableView时,其他单元格的样式也不同。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

细胞被重复使用。你需要处理所有可能性。如果updateUI处于活动状态,则您的myObject方法会更改单元格,但如果不是,则不会尝试重置单元格。

您需要以下内容:

func updateUI(myObject: MyObject){
    if myObject.isActive { 
        selectedCell()
    } else {
        resetCell()
    }
}

并添加:

func resetCell() {
    // Set the cell's UI as needed
}

另一个选项是覆盖表格单元类的prepareForReuse方法。该方法应该将单元格重置为其初始状态。