0
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】 UIColor extensionに任意の色を定義する

Posted at

#はじめに
ダークモードとライトモードで色が変わる、システムで提供されてるUIColor(.systemBackground 等) を自分で指定する方法がありましたので共有します

#UIColor Extension
UIColor を拡張して、以下のようなコードを書きます

import UIKit
extension UIColor {
    class var dynamicColor: UIColor {
        get {
            .init(dynamicProvider: { (traitCollection) -> UIColor in
                switch traitCollection.userInterfaceStyle {
                case .dark:
                    return .systemRed
                case .light:
                    return .systemBlue
                case .unspecified:
                    return .systemBlue
                @unknown default: return .systemBlue
                }
            })
        }
    }
}

#使用法
システムカラーと同様に記述するように使えます

class myViewController: UIViewController {
    override func viewDidLoad() {
        let button = UIButton()
        button.backgroundColor = .dynamicColor
    }
}

このようにUIColorを拡張することでも使用することができます

extension UIColor {
    class var dynamicColor: UIColor {
        get {
            .init(dynamicProvider: { (traitCollection) -> UIColor in
                return UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.1)
            })
        }
    }
}
0
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
0
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?