【问题标题】:Change tableview row text and image color更改 tableview 行文本和图像颜色
【发布时间】:2016-09-17 15:40:35
【问题描述】:

我有一个 tableView。在那我创建了自定义单元格。现在我想达到与图片所示完全相同的效果。我尝试了很多使用 selectionStyle 和其他东西,但我没有成功。

我想更改背景颜色、字体颜色和图像颜色。我怎样才能做到这一点?这是我的 UITableViewCell 的代码。

    import UIKit

public class BaseTableViewCell : UITableViewCell {
    class var identifier: String { return String.className(self) }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)


    }

    public override func awakeFromNib() {
        self.selectionStyle = UITableViewCellSelectionStyle.Gray
    }


    public class func height() -> CGFloat {
        return 40
    }

    public func setData(data: Any?, image : String!, alignment: NSTextAlignment!, font: UIColor) {

        self.textLabel?.font = UIFont(name: "Montserrat-Light", size: 12)
        self.textLabel?.textAlignment = alignment
        self.textLabel?.textColor = font

        if let menuText = data as? String {
            self.textLabel?.text = menuText
        }

        self.imageView?.image = UIImage(named: image)
    }

    override public func setHighlighted(highlighted: Bool, animated: Bool) {
        if highlighted {


        } else {
            self.alpha = 1.0
        }
    }

    // ignore the default handling
    override public func setSelected(selected: Bool, animated: Bool) {

    }

}

谢谢。

【问题讨论】:

  • 当你点击那个单元格时,它应该会这样改变......这是你的问题
  • 是的。它应该像那样改变。 @Uday.M

标签: ios swift uitableview highlight


【解决方案1】:

添加这个:

override public func setSelected(selected: Bool) {
    super.setSelected(selected)
    // Do your customization here

    // changing text color
    self.textLabel?.textColor = selected ? UIColor.blueColor() : UIColor.blackColor()
}

【讨论】:

  • 谢谢。这会改变背景颜色,但我也想改变字体颜色。 @鲍比
  • 如何更改图像颜色?
  • override public func setHighlighted(highlighted: Bool, animated: Bool) { if highlight { self.alpha = 0.4 } else { self.alpha = 1.0 } } 如果我是这样做也会影响图像。
  • "highlited" 在用户触摸单元格时执行。如果你想在触摸后保持效果,比如一个部分,使用我的解决方案,否则,用 setHighlighted 做同样的事情。要更改图像颜色,您可以更改图像资源,或者更改 imageView.tintColor,如果您的图像呈现为模板
  • 尝试在更改 tintColor 之前添加它:imageView.image = imageView.image?.imageWithRenderingMode(.AlwaysTemplate)
【解决方案2】:

覆盖 public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: true)

     self.textLabel?.textColor = selected ? UIColor.blue : UIColor.black
     self.imageView?.tintColor = selected ? UIColor.blue : UIColor.black

imageView?.image = imageView?.image!.withRenderingMode(.alwaysTemplate) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2021-08-22
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多