LoginSignup
9
9

More than 5 years have passed since last update.

[Swift]Buttonの色を変える方法

Last updated at Posted at 2017-12-03

Swiftでボタンの色やテキストを変えるときに、手間取ったのでメモ。
やりたいことは、タップしたときにボタンの背景色とテキストの色を変更させたい。
その際に、ボタンの色を確認して、処理を行う。

viewcontroller.swift
    //タップした時の挙動
    @IBAction func number4tapped(_ sender: CustomButton) {
        print("ss")
        if self.number4button.backgroundColor == UIColor.white {
            number4button.backgroundColor = UIColor(red:0.96, green:0.55, blue:0.15, alpha:1.0)
            number4button.setTitleColor(UIColor.white, for: .normal)
        }
    }

storyboard上でoutlet接続した上で、タップした際に「backgroundColor」と「setTitleColor」でそれぞれ、背景色とテキストの色を変更。

ちなみに、xcode上でボタンの背景色を設定できるが、それを「default」のままにしておくと、白色と認識されないので、処理が走りません。初めて知った・・・

コードで書いた方がいいのかなと思いつつ、storyboard使っちゃいますね。
時間あるときに、コードオンリーで書いてみよう。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9