4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift UIButtonの背景色をHighlightで変わるようにする

Last updated at Posted at 2020-03-15

#単色のUIImage生成
SwiftのUIButtonのtitleColorstateによって動的に変えることができますが、背景色は変えられません。
そのため、動的に変更することが可能な、単色のUIImageを背景に設定することで背景を動的に変更するようにします。

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(UIColor(red: 1, green: 1, blue: 1, alpha: 0.8).cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

#使い方
任意の場所でこのように書くと任意の色で設定することができます!

    let button = UIButton()
    button.setBackgroundImage(image, for: .normal)
    button.setBackgroundImage(image, for: .highlighted)
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?