1
1

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.

UIButtonの押下(ハイライト)時の色を設定する方法

Posted at

UIButtonの押下時の色の付け方が特殊だったのでメモ。

方法1: UIButtonのextensionにメソッドを生やす


extension UIButton {
    
    func setHighLightedColor(color: UIColor) {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(rect)
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        setBackgroundImage(image, for: .highlighted)
    }
    
}

使う時↓


    override func viewDidLoad() {
        super.viewDidLoad()
        editButton.setHighLightedColor(color: .highLighted)
    }

方法2: カスタムクラスを作成する


class CustomHighLightedButton: UIButton {

    // 押下(highlighted)時に統一したい色
    let hightLightedColor = UIColor(hex: 000000, alpha: 0.3)

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
        clipsToBounds = true
        setBackgroundImage(createImageFromUIColor(color: hightLightedColor), for: .highlighted)
    }
    
    private func createImageFromUIColor(color: UIColor) -> UIImage {
      let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
      UIGraphicsBeginImageContext(rect.size)
      if let context = UIGraphicsGetCurrentContext() {
          context.setFillColor(color.cgColor)
          context.fill(rect)
      }
      let image = UIGraphicsGetImageFromCurrentImageContext()!
      UIGraphicsEndImageContext()
      return image
    }

}

※ clipsToBoundsを書かないと押下時に色が変わりません

終わりに

細かいところですが、ボタン押下時の色も重要な項目だと思うので、これを機会に設定してみてはいかがでしょうか。

参考: https://qiita.com/akatsuki174/items/c0b8b5126b6c12f62001

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?