Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tạo nhiều style trong UITextView trên iOS App

Để 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ách tạo nhiều style trong UITextView trên iOS App

Các Attribute Key phổ biến

KeyKiểuMô tả
.fontUIFontFont chữ
.foregroundColorUIColorMàu chữ
.backgroundColorUIColorMàu nền chữ
.kernNSNumber (float)Khoảng cách giữa các ký tự
.strikethroughStyleNSNumber (int)Gạch ngang (1 = single)
.underlineStyleNSNumber (int)Gạch dưới
.linkURL/StringLink tap được (cần isSelectable=true, isEditable=false)
.paragraphStyleNSParagraphStyleCă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).