Để hiển thị văn bản với nhiều style (font, màu, kích thước...) trong một UITextView, dùng NSAttributedString gán cho property attributedText.
Code ví dụ
let textView = UITextView()
textView.isScrollEnabled = true
textView.isUserInteractionEnabled = true
textView.frame = CGRect(x: 10, y: 25, width: view.frame.width - 20, height: 150)
// Style 1: Xanh, size 16
let attr1: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16),
.foregroundColor: UIColor.systemBlue
]
// Style 2: Đỏ, size 20, bold
let attr2: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: 20),
.foregroundColor: UIColor.systemRed
]
// Tạo attributed strings
let str1 = NSAttributedString(string: "Tiêu đề: ", attributes: attr1)
let str2 = NSAttributedString(string: "Nội dung quan trọng\n", attributes: attr2)
let str3 = NSAttributedString(string: "Văn bản bình thường tiếp theo.", attributes: attr1)
// Gộp lại
let combined = NSMutableAttributedString()
combined.append(str1)
combined.append(str2)
combined.append(str3)
// Gán cho textView
textView.attributedText = combined
view.addSubview(textView)
Kết quả

Các Attribute Key phổ biến
| Key | Kiểu | Mô tả |
|---|---|---|
.font | UIFont | Font chữ |
.foregroundColor | UIColor | Màu chữ |
.backgroundColor | UIColor | Màu nền chữ |
.kern | NSNumber (float) | Khoảng cách giữa các ký tự |
.strikethroughStyle | NSNumber (int) | Gạch ngang (1 = single) |
.underlineStyle | NSNumber (int) | Gạch dưới |
.link | URL/String | Link tap được (cần isSelectable=true, isEditable=false) |
.paragraphStyle | NSParagraphStyle | Căn lề, line spacing, first line indent... |
Paragraph Style ví dụ
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
paragraph.lineSpacing = 8
paragraph.firstLineHeadIndent = 20
let attr: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16),
.paragraphStyle: paragraph
]
Mẹo
- Dùng
NSMutableAttributedStringđể append, insert, delete, replace range. - Để edit được attributed text:
textView.allowsEditingTextAttributes = true. - HTML -> AttributedString:
NSAttributedString(htmlData: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil).