2014-12-23 33 views
15

Tôi có thể đặt attributedTitle cho số UIControlState, nhưng làm cách nào để đặt màu tiêu đề được phân bổ cho số UIControlState?Làm cách nào để bạn đặt Màu tiêu đề phân bổ cho trạng thái trong Swift

+0

Trong tiêu đề của bạn thuộc tính từ điển: 'NSForegroundColorAttributeName: someColor' – Ian

+0

Phải, mà hoạt động tốt, nhưng điều đó không cho phép tôi đặt màu dựa trên trạng thái kiểm soát được chọn. – landing

Trả lời

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

câu trả lời tuyệt vời. câu hỏi tuyệt vời. Tôi đã có câu hỏi của riêng mình khoảng 90% đã hoàn thành và tôi đã thấy điều này. Chắc chắn đã trả lời câu hỏi của tôi. – Nate4436271

+0

@NatashaTheRobot bạn có thể vui lòng giúp tôi nó không hoạt động trong trường hợp được chọn ở đây không? –

4

Swift 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) 

Swift 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

Xin chào @kuzdu Tôi đã sử dụng mã này nhưng không hoạt động trong trường hợp đã chọn. bạn có thể giải thích toàn bộ bước không? –

Các vấn đề liên quan