我有一个自定义的Tableview
单元格,在那个单元格中有一个标签。
当您选择一个单元格时,我希望能够更改标签。
如何在UITableviewCell
中引用自定义didSelectRowAtIndexPath
标签
在目标C中,为了在didSelectRowAtIndexPath
中引用我的自定义单元格,我将使用以下内容:
MPSurveyTableViewCell *cell = (MPSurveyTableViewCell *)[tableViewcellForRowAtIndexPath:indexPath];
cell.customLabel.TextColor = [UIColor redColor];
为了取得同样的结果,我必须迅速做些什么呢?
发布于 2015-06-24 10:14:43
你只需要把相同的代码翻译成Swift。
var myCell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
myCell.customLabel.textColor = UIColor.redColor()
发布于 2016-05-07 05:57:57
上面的答案是不完整的
因为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)
}
发布于 2017-01-13 16:39:33
swift 3 xcode 8
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let Cell = tableView.cellForRow(at: indexPath)
Cell?.textLabel?.textColor = UIColor.red // for text color
Cell?.backgroundColor = UIColor.red // for cell background color
}
https://stackoverflow.com/questions/31023737
复制相似问题