2017-04-11 21 views
0

タイトルラベルの色を白に変更するボタンを作成しようとしています。私のコードはそうです:タイトルラベルのテキストの色がUIButtonで正しくアニメートされない

import UIKit 

class AlertStyleButton: UIButton { 

    var buttonColor: UIColor? 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setup() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     setup() 
    } 

    func setup() { 
     buttonColor = titleColor(for: .normal) 
    } 

    override var isHighlighted: Bool { 
     didSet { 
      guard let buttonColor = buttonColor else { 
       return 
      } 
      if isHighlighted { 
       UIView.animate(withDuration: 0.1, animations: { 
        self.setTitleColor(UIColor.white, for: UIControlState()) 
        self.backgroundColor = buttonColor 
       }) 
      } else { 
       UIView.animate(withDuration: 0.1, animations: { 
        self.setTitleColor(buttonColor, for: UIControlState()) 
        self.backgroundColor = UIColor.white 
       }) 
      } 
     } 
    } 


} 

ボタンが押されて押し込まれると、ボタンの色が正しく動くようです。ただし、テキストは白色にアニメートされません。私はここで間違って何をしていますか?

+0

(のためのbuttonColor、:.normal)self.setTitleColorに変更 – karthikeyan

+1

http://stackoverflow.com/questions/27577443/is-it-possible-to-animate-uilabels-textcolor -change –

+0

@karthikeyanは何の違いもありません – KexAri

答えて

0

UIButtonのタイトルカラーを設定するには、setTitleColor: forState:メソッドを明示的に使用する必要があります。そのような例:

var buttonTextColor: UIColor! 
var buttonBgColor: UIColor! 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    setup() 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    setup() 
} 

func setup() { 
    buttonBgColor = UIColor.white // set whatever color you like 
    buttonTextColor = UIColor.black // set whatever color you like 
    backgroundColor = buttonBgColor 
    setTitleColor(buttonTextColor, for: .normal) 
    setTitleColor(buttonBgColor, for: .highlighted) 
} 

override var isHighlighted: Bool { 
    didSet { 
     if isHighlighted { 
      UIView.animate(withDuration: 0.1, animations: { 
       self.backgroundColor = self.buttonTextColor 
      }) 
     } else { 
      UIView.animate(withDuration: 0.1, animations: { 
       self.backgroundColor = self.buttonBgColor 
      }) 
     } 
    } 
} 
+0

上記のコードを試してみてください^それは黒い背景アニメーションをうまく示していますが、テキストは白くアニメーション化されません。 – KexAri

関連する問題