UIAlertController custom font, size, color

后端 未结 25 2150
遥遥无期
遥遥无期 2020-11-22 09:06

I am using new UIAlertController for showing alerts. I have this code:

// nil titles break alert interface on iOS 8.0, so we\'ll be using empty strings
UIAle         


        
25条回答
  •  醉话见心
    2020-11-22 09:49

    I just completed a replacement for UIAlertController. This is the only sensible way to go, I think:


    Old

    Here's my method in Swift which mashes up a lot of information from answers here

    func changeAlert(alert: UIAlertController, backgroundColor: UIColor, textColor: UIColor, buttonColor: UIColor?) {
        let view = alert.view.firstSubview().firstSubview()
        view.backgroundColor = backgroundColor
        view.layer.cornerRadius = 10.0
    
        // set color to UILabel font
        setSubviewLabelsToTextColor(textColor, view: view)
    
        // set font to alert via KVC, otherwise it'll get overwritten
        let titleAttributed = NSMutableAttributedString(
            string: alert.title!,
            attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(17)])
        alert.setValue(titleAttributed, forKey: "attributedTitle")
    
    
        let messageAttributed = NSMutableAttributedString(
            string: alert.message!,
            attributes: [NSFontAttributeName:UIFont.systemFontOfSize(13)])
        alert.setValue(messageAttributed, forKey: "attributedMessage")
    
    
        // set the buttons to non-blue, if we have buttons
        if let buttonColor = buttonColor {
            alert.view.tintColor = buttonColor
        }
    }
    
    func setSubviewLabelsToTextColor(textColor: UIColor, view:UIView) {
        for subview in view.subviews {
            if let label = subview as? UILabel {
                label.textColor = textColor
            } else {
                setSubviewLabelsToTextColor(textColor, view: subview)
            }
        }
    }
    

    This works in some situations perfectly, and in others it's a total fail (the tint colors do not show as expected).

提交回复
热议问题