UIAlertController テキスト配置 質問する

UIAlertController テキスト配置 質問する

iOS 8 の UIAlertController 内に表示されるメッセージの配置を変更する方法はありますか?

サブビューにアクセスして UILabel 用に変更することはもうできないと思います。

ベストアンサー1

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")

タイトルでも同様のことができます。代わり"attributedTitle"にを使用します。"attributedMessage"

Swift 3 アップデート

上記は Swift 3 でも動作しますが、コードを次のように少し変更する必要があります。

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 アップデート

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 アップデート

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")

おすすめ記事