迅速.选中后更改自定义Tableview单元格标签的颜色

use*_*353 10 uitableview custom-cell didselectrowatindexpath ios swift

Tableview在swift中有一个Custom 单元格,在该单元格中有一个标签.

我希望能够在选择单元格时更改标签.

如何在中引用我的自定义UITableviewCell标签didSelectRowAtIndexPath

在Objective C中引用我的自定义单元格,didSelectRowAtIndexPath我将使用以下内容:

MPSurveyTableViewCell *cell = (MPSurveyTableViewCell *)[tableViewcellForRowAtIndexPath:indexPath];
cell.customLabel.TextColor = [UIColor redColor]; 
Run Code Online (Sandbox Code Playgroud)

我必须在swift中做些什么才能达到相同的效果?

Rei*_*ica 12

您只需将相同的代码转换为Swift即可.

var myCell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
myCell.customLabel.textColor = UIColor.redColor()
Run Code Online (Sandbox Code Playgroud)


Wat*_*rds 7

以上答案不完整

因为UITableView会重复使用单元格,所以需要检查单元格是否被选中并在cellForRowAtIndexPath中适当调整颜色.可能存在拼写错误,但这是完整的答案:

func tableView(tableView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifierHere", forIndexPath: indexPath) as! MPSurveyTableViewCell 

    // setup your cell normally

    // then adjust the color for cells since they will be reused
    if cell.selected {
        cell.customLabel.textColor = UIColor.redColor()
    } else {
        // change color back to whatever it was
        cell.customLabel.textColor = UIColor.blackColor()
    }

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
    cell.customLabel.textColor = UIColor.redColor()
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)

}

func tableView(tableView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell

    // change color back to whatever it was
    cell.customLabel.textColor = UIColor.blackColor()
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)

}
Run Code Online (Sandbox Code Playgroud)