如何设置UIButton的标题文本颜色?

coo*_*mac 106 uibutton ios swift

我尝试更改按钮的文本颜色,但它仍然保持白色.

isbeauty = UIButton()
isbeauty.setTitle("Buy", forState: UIControlState.Normal)
isbeauty.titleLabel?.textColor = UIColorFromRGB("F21B3F")
isbeauty.titleLabel!.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 25)
isbeauty.backgroundColor = UIColor.clearColor()
isbeauty.layer.cornerRadius = 5
isbeauty.layer.borderWidth = 1
isbeauty.layer.borderColor = UIColorFromRGB("F21B3F").CGColor
isbeauty.frame = CGRectMake(300, 134, 55, 26)
isbeauty.addTarget(self,action: "first:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(isbeauty)
Run Code Online (Sandbox Code Playgroud)

我也试过把它改成红色,黑色,蓝色,但什么也没发生.

luk*_*302 238

您必须使用func setTitleColor(_ color: UIColor?, forState state: UIControlState)与设置实际标题文本相同的方式.文件

isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

  • 我的代码:yourButtonName.setTitleColor(UIColor.red,for:.normal) (4认同)
  • 我相信,从xcode 9开始,它现在是".normal"而不是".Normal" (3认同)

Vya*_*lav 101

Swift 3,Swift 4

改进评论.这应该工作:

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))
Run Code Online (Sandbox Code Playgroud)


han*_*som 8

设置按钮标题颜色的示例

btnDone.setTitleColor(.black, for: .normal)
Run Code Online (Sandbox Code Playgroud)

  • 我和你的答案之间的区别是什么? (6认同)
  • 很明显——颜色 (2认同)