UIAlertViewController Text Alignment

1*5koxNC03BSLLt6Urass5yA.png

Small tip

You might wanna change the text alignment of the alert controller. Let’s say, change the alignment from center to right. Then the following is for you.

Just simply open a playground and run these code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import UIKit
import XCPlayground
import PlaygroundSupport

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: "Left Position, correct?",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font : UIFont.preferredFont(forTextStyle: .body),
NSAttributedString.Key.foregroundColor : UIColor.black
]
)

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

let viewController = UIViewController()
PlaygroundPage.current.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.

[References]

Introduction to Key-Value Observing Programming Guide

UIAlertViewController Text Alignment

1*5koxNC03BSLLt6Urass5yA.png

Small tip

You might wanna change the text alignment of the alert controller. Let’s say, change the alignment from center to right. Then the following is for you.

Just simply open a playground and run these code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import UIKit
import XCPlayground
import PlaygroundSupport

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: "Left Position, correct?",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font : UIFont.preferredFont(forTextStyle: .body),
NSAttributedString.Key.foregroundColor : UIColor.black
]
)

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

let viewController = UIViewController()
PlaygroundPage.current.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.

[References]

Introduction to Key-Value Observing Programming Guide