2014-12-23 114 views
15

我可以將attributedTitle設置爲UIControlState,但是如何設置UIControlState的標題標題顏色?如何在Swift中設置狀態的標題標題顏色

+0

在你的title屬性詞典:'NSForegroundColorAttributeName:someColor' – Ian

+0

權,工作正常,但是,這並不讓我根據所設置的顏色。選擇控制狀態 – landing

回答

34
// 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) 
+0

很好的答案。很好的問題。我有我自己的問題完成了90%,我看到了這一點。絕對回答了我的問題。 – Nate4436271

+0

@NatashaTheRobot你可以請幫我在這裏選擇的情況下不工作? –

4

斯威夫特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) 

斯威夫特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) 
+0

嗨@kuzdu我已經使用這段代碼,但它不能在選定的情況下工作。你能解釋一下嗎? –

相關問題