如何在Swift中为State设置归属标题颜色

lan*_*ing 25 uibutton swift

我可以设置attributedTitlefor a UIControlState,但是如何设置属性标题的颜色UIControlState呢?

Nat*_*bot 51

// create the button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = UIColor.yellowColor()

// set the attributed title for different states

// .Selected
let mySelectedAttributedTitle = NSAttributedString(string: "Click Here",
    attributes: [NSForegroundColorAttributeName : UIColor.greenColor()])
button.setAttributedTitle(mySelectedAttributedTitle, forState: .Selected)

// .Normal
let myNormalAttributedTitle = NSAttributedString(string: "Click Here",
    attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
button.setAttributedTitle(myNormalAttributedTitle, forState: .Normal)
Run Code Online (Sandbox Code Playgroud)


kuz*_*zdu 14

斯威夫特4

    // create the button
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    button.backgroundColor = UIColor.yellow

    // set the attributed title for different states

    // .Selected
    let mySelectedAttributedTitle = NSAttributedString(string: "Click Here",
                                                       attributes: [NSAttributedStringKey.foregroundColor : UIColor.green])
    button.setAttributedTitle(mySelectedAttributedTitle, for: .selected)

    // .Normal
    let myNormalAttributedTitle = NSAttributedString(string: "Click Here",
                                                     attributes: [NSAttributedStringKey.foregroundColor : UIColor.blue])


    button.setAttributedTitle(myNormalAttributedTitle, for: .normal)
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

// create the button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = UIColor.yellow

// set the attributed title for different states

// .Selected
let mySelectedAttributedTitle = NSAttributedString(string: "Click Here",
                                               attributes: [NSForegroundColorAttributeName : UIColor.green])
button.setAttributedTitle(mySelectedAttributedTitle, for: .selected)

// .Normal
let myNormalAttributedTitle = NSAttributedString(string: "Click Here",
                                             attributes: [NSForegroundColorAttributeName : UIColor.blue])


button.setAttributedTitle(myNormalAttributedTitle, for: .normal)
Run Code Online (Sandbox Code Playgroud)

  • @kuzdu,您好,我已经使用此代码,但在某些情况下无法正常工作。您能解释一下整个步骤吗? (3认同)