使用自定义单元格swift更改颜色detailTextLabel tableView

时间:2015-03-16 07:42:37

标签: ios xcode swift

我已经创建了这样的自定义tableView,如果选择了行,我想更改detailTextLabel

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

    var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell

    if (cell == nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "CELL")
        cell!.backgroundColor = UIColor.clearColor()

        let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height))
        selectedBackgroundView.backgroundColor = UIColor.lightGrayColor()
        cell!.selectedBackgroundView = selectedBackgroundView

        let textHeader = UILabel(frame: CGRectMake(45, -3, 160, 40))
        textHeader.contentMode = UIViewContentMode.ScaleAspectFit
        textHeader.text = self.menus[indexPath.row]
        textHeader.textColor = UIColor.whiteColor()
        textHeader.font = UIFont(name:"HelveticaNeue-Light", size: 16)
        cell?.contentView.addSubview(textHeader)

        let textDetail = UILabel(frame: CGRectMake(45, 13, 160, 40))
        textDetail.contentMode = UIViewContentMode.ScaleAspectFit
        textDetail.text = self.detailmenus[indexPath.row]
        textDetail.textColor = UIColor(red: 255/255, green: 198/255, blue: 0/255, alpha: 1)
        textDetail.font = UIFont(name:"HelveticaNeue-Light", size: 12)
        cell?.contentView.addSubview(textDetail)

        let imageView = UIImageView(frame: CGRectMake(10, 10, 25, 25))
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        imageView.clipsToBounds = true
        imageView.image = UIImage(named: thumbils[indexPath.row])
        cell?.contentView.addSubview(imageView)
    }

    return cell!
}

我试图改变这样的文字细节标签,但它没有用

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var colorSelected = UIColor(red: 3/255, green: 134/255, blue: 27/255, alpha: 1)
    tableView.cellForRowAtIndexPath(indexPath)?.detailTextLabel?.textColor = colorSelected 
}

如何更改detailTextLabel颜色?

1 个答案:

答案 0 :(得分:1)

你应该在界面构建器中创建你的单元格,创建cellForRowAtIndexPath中的每个组件是一个坏主意,事实上这就是你应该做的。

子类UITableViewCell,在界面构建器中使用它,为该标签创建插座,在界面构建器中使用此单元格,在其上放置标签,将插座连接到该标签,现在您可以访问该标签。现在您不必在cellForRowAtIndexPath中创建该标签,因为您是在界面构建器中创建的。

下一步非常简单,你可以非常正确地使用它,但你的detailTextLabel没有设置。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var colorSelected = UIColor(red: 3/255, green: 134/255, blue: 27/255, alpha: 1)
    tableView.cellForRowAtIndexPath(indexPath)?.detailTextLabel?.textColor = colorSelected 
}

在tableview上查看本教程:http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout跳到部分“创建一个基本的自定义单元格”,你应该知道如何做到这一点

相关问题