以编程方式设置UIButton的文本颜色

3

我想改变我的表视图页脚中按钮的文本颜色。以下是我正在使用但无效的代码:

override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
    footerView.backgroundColor = UIColor.blackColor()

    let rgbValue = 0x4097d4
    let color = Util.getColor(rgbValue)




    let button   = UIButton(type: UIButtonType.System) as UIButton
    button.frame = CGRectMake(0, 0, 414, 65)

    button.setTitle("my Button", forState: UIControlState.Normal)
    button.titleLabel?.textColor = UIColor.whiteColor()
    button.titleLabel?.font = UIFont(name: "Montserrat-Regular", size: 20.0)



     button.backgroundColor =  UIColor( red: CGFloat(color[0]), green: CGFloat(color[1]), blue:CGFloat(color[2]), alpha: 1.0 )



    footerView.addSubview(button)


    return footerView
}

override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 40.0
}

一个问题是文本颜色不改变,另一个问题是我的表格视图中有很多静态行。我正在将按钮固定在底部,但问题是当屏幕到达末尾时,如果我点击屏幕并向上拖动屏幕,它仍然会显示一些白色空间在按钮之后。


尝试过其他类型的 UIButtonType 吗? - Travis Griggs
1个回答

14

不要直接设置标签的颜色,使用-setTitleColor:forState:方法。

button.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)

非常感谢,它有效了。 - hellosheikh
你能回答我的另一个问题吗?如果可能的话,你能给我关于下一个问题的小提示吗? - hellosheikh
关于另一个问题,取决于你想要的行为。如果你不想让页脚与表格视图一起滚动,则参考 这个问题。如果你想要它滚动,但希望按钮的颜色超出按钮底部,那么你应该在按钮下方创建一个额外的纯色视图来填充空间。 - Noah Witherspoon
感谢您的回答。我已经解决了这个问题。实际上,我应该取消选中“bounce”属性,现在我已经这样做了。 - hellosheikh
非常感谢...救了我的一天...之前我尝试过button.titleLabel?.textColor = .red,但在从nib唤醒时它并没有起作用...但是你的方法正如预期地工作了。 - Rakshitha Muranga Rodrigo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接