首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >斯威夫特。选择自定义表视图单元格标签时更改颜色

斯威夫特。选择自定义表视图单元格标签时更改颜色
EN

Stack Overflow用户
提问于 2015-06-24 10:08:51
回答 6查看 19K关注 0票数 10

我有一个自定义的Tableview单元格,在那个单元格中有一个标签。

当您选择一个单元格时,我希望能够更改标签。

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

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

代码语言:javascript
运行
复制
MPSurveyTableViewCell *cell = (MPSurveyTableViewCell *)[tableViewcellForRowAtIndexPath:indexPath];
cell.customLabel.TextColor = [UIColor redColor]; 

为了取得同样的结果,我必须迅速做些什么呢?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2015-06-24 10:14:43

你只需要把相同的代码翻译成Swift。

代码语言:javascript
运行
复制
var myCell = tableView.cellForRowAtIndexPath(indexPath) as! MPSurveyTableViewCell
myCell.customLabel.textColor = UIColor.redColor()
票数 12
EN

Stack Overflow用户

发布于 2016-05-07 05:57:57

上面的答案是不完整的

因为UITableView重用单元格,所以需要检查是否选择了单元格,并在cellForRowAtIndexPath中适当地调整颜色。可能会有打字,但这是完整的答案:

代码语言:javascript
运行
复制
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)

}
票数 8
EN

Stack Overflow用户

发布于 2017-01-13 16:39:33

swift 3 xcode 8

代码语言:javascript
运行
复制
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
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31023737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档