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

153

我尝试更改按钮文本的颜色,但它仍然是白色。

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)

我也尝试将其更改为红色、黑色、蓝色,但什么都没有发生。

11个回答

359

您需要像设置实际标题文本一样使用 func setTitleColor(_ color: UIColor?, for state: UIControl.State)文档

isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)

为了可读性,我倾向于不限定枚举类型,但这只是我的个人偏好。 - Tyler
@styler1972 我也更喜欢这样 - 显然我最初回答时并不知道。 - luk2302
1
isbeauty.setTitleColor(UIColorFromRGB(rgbValue: "F21B3F"), for: .Normal) - Arunabh Das
3
我相信从Xcode 9开始,现在应该是使用".normal"而不是".Normal"。 - Buddhisthead
4
你的代码: yourButtonName.setTitleColor(UIColor.red, for: .normal) - Dev Gurung
如果您在Interface Builder中将文本的颜色设置为除默认值以外的任何颜色,它将阻止此方法的正常运行。 - Jordan Réjaud

127

Swift UI解决方案

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3、Swift 4、Swift 5

为了改进注释。 这个应该可以工作:

button.setTitleColor(.red, for: .normal)

18

设置按钮标题颜色的示例

btnDone.setTitleColor(.black, for: .normal)

13
我的答案和你的有什么区别? - Vyacheslav
2
很明显 - 颜色 - janaz

3
func setTitleColor(_ color: UIColor?, 
               for state: UIControl.State)

参数:

color:
指定状态下标题的颜色。

state:
使用指定颜色的状态。可能的值在UIControl.State中描述。

示例:

let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)

2
这是适用于Swift 5的答案。如果你想使用内置的颜色之一,那么你可以简单地使用。
button.setTitleColor(.red, for: .normal)

如果您想要一些自定义颜色,则首先创建一个如下所示的UIColor扩展。
import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

然后按以下方式将其用于您的按钮。

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

提示:您可以使用此方法来存储 rgba 颜色代码中的自定义颜色,并在整个应用程序中重复使用。

1

如果您使用没有NSAttribute的按钮,则可以通过以下方式设置按钮的标题和颜色:

yourButtonName.setTitle("Your Title", for: .normal)

enterCustomAmount.setTitleColor(.gray, for: .normal)

但如果您在按钮属性中使用NSAttribute,则需要先为按钮设置属性。

var myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.init(hexString: "#FFAEA9")]

或者,如果有多个属性,您可以使用逗号分隔符,例如:
var myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.init(hexString: "#FFAEA9"), NSAttributedString.Key.font: UIFont(name: "Dubai-Medium", size: 16) ]

并将其分配给您的UIButton,如下所示

 let myString = "Your title"
            let text = NSAttributedString(string: myString, attributes: myAttribute)
            enterCustomAmount.setAttributedTitle(text, for: .normal)

0
你可以使用十六进制代码来设置UIButton的标题颜色。
btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)

添加了这个扩展类以支持字符串颜色代码

public extension UIColor {
        convenience init(hexString: String, alpha: CGFloat = 1.0) {
            let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
            let scanner = Scanner(string: hexString)
            
            if (hexString.hasPrefix("#")) {
                scanner.currentIndex = .init(utf16Offset: 1, in: hexString)
            }
            
            var color: UInt64 = 0
            scanner.scanHexInt64(&color)
            let mask = 0x000000FF
            let r = Int(color >> 16) & mask
            let g = Int(color >> 8) & mask
            let b = Int(color) & mask
            let red   = CGFloat(r) / 255.0
            let green = CGFloat(g) / 255.0
            let blue  = CGFloat(b) / 255.0
            
            self.init(red:red, green:green, blue:blue, alpha:alpha)
        }
    }

UIColor没有提供hexString:的初始化方法。 - HangarRash
这个初始化函数是一个扩展函数。 - Md. Shofiulla

0

设置标题颜色

btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)

0

提到单选按钮,你也可以使用分段控件来实现:

步骤1: 将一个分段控件拖动到你的视图中 在属性检查器中更改两个分段的标题,例如“男”和“女”

步骤2: 在代码中创建输出口和操作

步骤3: 为将来使用创建一个变量以包含选择的数据

在代码中按照以下方式操作:

@IBOutlet weak var genderSeg: UISegmentedControl!

var genderPick : String = ""


 @IBAction func segAction(_ sender: Any) {

    if genderSeg.selectedSegmentIndex == 0 {
         genderPick = "Male"
        print(genderPick)
    } else if genderSeg.selectedSegmentIndex == 1 {
        genderPick = "Female"
          print(genderPick)
    }
}

-1

改变文本颜色

button.titleLabel.textColor = UIColor.grayColor()

要改变状态,在按钮按下时添加以下内容 -

button.enabled = true

IBAction方法应该像这样 -

@IBAction func buttonTapped(sender : UIButton!) {
    sender.enabled = false
}

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