UIAlertController Text Alignment

Sometimes you might wanna change the alert controller’s text alignment, let say, from center to right. Then following tip is for you.

Just simply open a playground and run these code

import UIKit
import XCPlayground

let alertView = UIAlertController(title: "Demo Alert", message: "", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

let paragraphStyle = NSMutableParagraphStyle()
// Here is the key thing!
paragraphStyle.alignment = .left

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

alertView.setValue(messageText, forKey: "attributedMessage")

let viewController = UIViewController()
XCPlaygroundPage.currentPage.liveView = viewController.view
viewController.present(alertView, animated: true, completion: nil)

The most important thing is the key “attributedMessage”, an alert controller can change its text alignment value by using this key.





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s