LoginSignup
8
2

More than 5 years have passed since last update.

UIAlertControllerの背景色(キャンセルボタン含む)を変更するextension

Last updated at Posted at 2018-09-24

UIAlertControllerの背景色を変更しようとした時に、テキストカラー変更やキャンセルボタン以外のカラー変更はたくさん記事を探すことができました。
ただ、キャンセルボタンも含めて背景色を変更する方法を探しづらかったのでメモしておきます。

extension

extension UIAlertController {
    func itemBackgroundColor(_ color: UIColor) {
        // ここでキャンセルボタン以外の背景色を変更
        let FirstSubview = self.view.subviews.first
        let AlertContentView = FirstSubview?.subviews.first
        for subview in (AlertContentView?.subviews)! {
            subview.backgroundColor = color
            subview.layer.cornerRadius = 10
            subview.alpha = 1
        }
        // ここでキャンセルボタンの背景色を変更
        if let cancelBackgroundViewType = NSClassFromString("_UIAlertControlleriOSActionSheetCancelBackgroundView") as? UIView.Type {
            cancelBackgroundViewType.appearance().subviewsBackgroundColor = color
        }
    }
}

extension UIView {
    private struct AssociatedKey {
        static var subviewsBackgroundColor = "subviewsBackgroundColor"
    }

    @objc dynamic var subviewsBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.subviewsBackgroundColor) as? UIColor
        }

        set {
            objc_setAssociatedObject(self,
                                     &AssociatedKey.subviewsBackgroundColor,
                                     newValue,
                                     .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            subviews.forEach { $0.backgroundColor = newValue }
        }
    }
}

使い方

let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.itemBackgroundColor(UIColor.black)
8
2
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
8
2