UIAlertController text alignment

前端 未结 8 1811
醉话见心
醉话见心 2020-12-05 04:07

Is there a way to change the alignment of the message displayed inside a UIAlertController on iOS 8?

I believe accessing the subviews and changing it for the UILabel

8条回答
  •  时光说笑
    2020-12-05 05:11

    I have successfully used the following, for both aligning and styling the text of UIAlertControllers:

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.Left
    
    let messageText = NSMutableAttributedString(
        string: "The message you want to display",
        attributes: [
            NSParagraphStyleAttributeName: paragraphStyle,
            NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody),
            NSForegroundColorAttributeName : UIColor.blackColor()
        ]
    )
    
    myAlert.setValue(messageText, forKey: "attributedMessage")
    

    You can do a similar thing with the title, if you use "attributedTitle", instead of "attributedMessage"

    Swift 3 update

    The above still works in Swift 3, but the code has to be slightly altered to this:

    let messageText = NSMutableAttributedString(
        string: "The message you want to display",
        attributes: [
            NSParagraphStyleAttributeName: paragraphStyle,
            NSFontAttributeName : UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
            NSForegroundColorAttributeName : UIColor.black
        ]
    )
    
    myAlert.setValue(messageText, forKey: "attributedMessage")
    

    Swift 4 update

    let messageText = NSMutableAttributedString(
        string: "The message you want to display",
        attributes: [
            NSAttributedStringKey.paragraphStyle: paragraphStyle,
            NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
            NSAttributedStringKey.foregroundColor: UIColor.black
        ]
    )
    
    myAlert.setValue(messageText, forKey: "attributedMessage")
    

    Swift 5 update

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = alignment
    let messageText = NSAttributedString(
        string: "message",
        attributes: [
            NSAttributedString.Key.paragraphStyle: paragraphStyle,
            NSAttributedString.Key.foregroundColor : UIColor.primaryText,
            NSAttributedString.Key.font : UIFont(name: "name", size: size)
        ]
    )
    
    myAlert.setValue(messageText, forKey: "attributedMessage")
    

提交回复
热议问题