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

时间:2015-06-27 11:20:15

标签: ios swift uibutton

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

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)

我也试过把它改成红色,黑色,蓝色,但没有发生任何事情。

8 个答案:

答案 0 :(得分:199)

您必须以设置实际标题文字的方式使用func setTitleColor(_ color: UIColor?, forState state: UIControlState)Docs

isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), forState: .Normal)

答案 1 :(得分:95)

Swift 3,Swift 4,Swift 5

改善评论。 这应该有效:

$(document).on({
    mouseenter: function () {
        $(this).css({'background-color':'#4d576c','color':'#fff'});
    },
    mouseleave: function () {
        if($(this).hasClass('showAccordion')){
        $(this).css({'background-color':'#4d576c','color':'#fff'});
    }else{
        $(this).css({'background-color':'#fff','color':'#000'});
    }   
    }
}, ".fc-row td");

答案 2 :(得分:6)

设置按钮标题颜色的示例

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

答案 3 :(得分:1)

这是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颜色代码中的自定义颜色,并在整个应用程序中重复使用它。

答案 4 :(得分:1)

public enum AreaToUse {

    private static final Map<Integer, AreaToUse> MAPPING = new HashMap<>();

    static {
        for(AreaToUse areaToUse : values()) {
            MAPPING.put(areaToUse.getQualified(), areaToUse);
        }
    }
    public static AreaToUse byQualified(int qualified) {
        return MAPPING.get(qualified);
    }
}

参数

  

颜色:
用于指定状态的标题的颜色。

     

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

示例

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

答案 5 :(得分:0)

指的是单选按钮,您也可以使用分段控制来做到这一点:

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

步骤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)
    }
}

答案 6 :(得分:0)

设置标题颜色

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

答案 7 :(得分:0)

您可以使用十六进制代码设置 UIButton 标题颜色

btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)
相关问题