Ios 如何设置UITableViewCell的不同样式?

Ios 如何设置UITableViewCell的不同样式?,ios,swift,uitableview,Ios,Swift,Uitableview,我正在尝试为TableView中的活动对象设置不同的样式。我试着为我的对象(myObject.isActive)设置一个标志,并像这样在我的自定义UITableViewCell中读取它 var myArray = [MyObject]() override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = ta

我正在尝试为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时,其他单元格的样式也不同。如何解决这个问题?

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

你需要像这样的东西:

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

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

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

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

你需要像这样的东西:

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

func resetCell() {
    // Set the cell's UI as needed
}
另一个选项是重写表格单元格类的
prepareforuse
方法。该方法应将单元格重置为其初始状态