LoginSignup
19
11

More than 5 years have passed since last update.

UIButton をタップした時の背景色を UIColor で指定する

Posted at

UIButtonハイライト時の色を指定する - Qiita と内容はほぼ同じです。

UIButton をタップした時の背景色を変えたくても、メソッドとしては setBackgroundImage があるだけで使い勝手が良くありません。
setBackgroundColor があると嬉しいですよね。

というわけで Extension です。

extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
        let image = color.image
        setBackgroundImage(image, for: state)
    }
}

extension UIColor {
    var image: UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        context.setFillColor(self.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

UIColor から UIImage を作って、それを setBackgroundImage しています。

使い方

let button = UIButton(type: .system)
button.setTitle("button", for: .normal)
button.setBackgroundColor(.gray, for: .highlighted)

Screen.gif

背景色が変わりました :tada:

19
11
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
19
11