簡體   English   中英

iOS 按鈕標題顏色不會改變

[英]iOS button title color won't change

我正在使用以下代碼動態創建一個 UIButton,它按照指定的樣式創建它。

let frame = CGRect(x: 10, y: 6, width: 60, height: 30 )    
let button = UIButton(frame: frame)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.whiteColor()
button.addTarget(self, action: "filterByCategory:", forControlEvents: UIControlEvents.TouchUpInside)
self.categoryScrollView.addSubview(button)

使用此按鈕,我想在點擊時切換樣式。 以下代碼更改背景顏色但不更改標題顏色。 知道為什么標題顏色不會改變嗎?

func filterByCategory(sender:UIButton) {

    if sender.backgroundColor != UIColor.blackColor() {
        sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
        sender.backgroundColor = UIColor.blackColor()
    } else {
        sender.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        sender.backgroundColor = UIColor.whiteColor()
    }

}

因為你的按鈕會變成回UIControlState.Normal你觸摸后,它成為.Highlighted ,然后.Normal

你應該設置sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)

sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState. Normal)

或者,只是為所有狀態設置它,因為你檢查了顏色

sender.setTitleColor(UIColor.whiteColor(), forState: [.Normal,.Selected,.Highlighted])

*編輯:上面不起作用,可以使用NSAttributedString代替

if self.loginButton.backgroundColor == UIColor.blackColor() {
            let tittle = NSAttributedString(string: "Login", attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
            loginButton.setAttributedTitle(tittle, forState: .Normal)
            loginButton.backgroundColor = UIColor.whiteColor()
        } else {
            let tittle = NSAttributedString(string: "Login", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            loginButton.setAttributedTitle(tittle, forState: .Normal)
            loginButton.backgroundColor = UIColor.blackColor()
        }

我已經找到超過 4 到 5 個小時的解決方案,但沒有找到任何東西並得出以下兩點結論:-

  • 如果您從 storyboard 提供標題並以編程方式或自定義 class 設置標題顏色,那么它將不起作用。 解決方案是
  1. 您可以使用簡單的 setTitleColor() 方法以編程方式設置標題並以編程方式更改其顏色。
  2. 或者您可以使用 storyboard 來設置標題和通過前景色設置顏色。
  3. 如果您使用的是 Custom Class,您可以使用 Inspectable 並以編程方式設置其值,並使用解決方案 1 設置標題的顏色。
  • 如果您不想執行此步驟,只需將按鈕類型更改為默認值,它將以您以編程方式或從 storyboard 設置 titleColor 的任何方式工作

對於斯威夫特3

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

從上面描述的問題。 我得出的結論是您創建的按鈕沒有標題,因此您看不到標題顏色的變化。

要解決此問題:-

  1. 為按鈕設置標題
  2. 使用 UIButton 屬性更改標題顏色 button.setTitleColor button.setTitleColor(.black, for: .normal)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM