+1

NSAttributedString to custom style of Text

1. Giới thiệu:

NSAttributedString quản lý chuỗi ký tự và tập hợp các thuộc tính (như font và kerning) được áp dụng cho các ký tự và dãy các ký tự trong chuỗi String. Tập hợp các ký tự và thuộc tính của nó được gọi là attributed string. Có 2 class được public:

  • NSAttributedString: Read-only attributed strings.
  • NSMutableAttributedString: cho phép thay đổi, chỉnh sửa attributed strings. Vậy chỉnh sửa thế nào, set giá trị ra sao để cho các đoạn Text trong ứng dụng trở nên sinh động và đẹp mắt hơn? Hãy đến với những ví dụ nho nhỏ dưới đây nhé.

2. Example:

Set các thuộc tính như: font, size, text effect, color, shadow và underline cho UILabel. Chỉ cần định nghĩa các attributed dưới dạng Dictionary và gán cho thuộc tính attributedText của UILabel là xong. 😃

if let titleFont = UIFont(name: "Copperplate", size: 30.0)  {
   let shadow : NSShadow = NSShadow()
   shadow.shadowOffset = CGSize(width: -2.0, height: -2.0)
   let attributes = [
          NSFontAttributeName : titleFont,
          NSUnderlineStyleAttributeName : 1,
          NSForegroundColorAttributeName : UIColor.white,
          NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
          NSStrokeWidthAttributeName : 3.0,
          NSShadowAttributeName : shadow] as [String : Any]
  let title = NSAttributedString(string: "NSAttributedString", attributes: attributes)
  let label = UILabel(frame: CGRect(x: (self.view.bounds.width - title.size().width) / 2, y: 80, width: title.size().width, height: title.size().height))
  label.attributedText = title
  view.addSubview(label)
}

Result:

3. Character Attributes:

  • NSFontAttributeName: Thay đổi Font của Text. Default là Helvetica(Neue) - 12 point *** NSParagraphStyleAttributeName:** Cho phép apply nhiều thuộc tính (như alignment, tab stops và line break) cho một đoạn văn bản(paragraph)
  • NSForegroundColorAttributeName: Thay đổi màu của Text trong quá trình rendering. Default là Black color.
NSForegroundColorAttributeName : UIColor.red

    • NSBackgroundColorAttributeName: Color của background text.
NSBackgroundColorAttributeName : UIColor.yellow

  • NSLigatureAttributeName: Kết hợp các character với nhau bằng các custom glyph tương ứng với các character đó. NSLigatureAttributeName value là Int. 1: default ligatures, 0: no ligatures, 2: all ligatures(không support trên iOS)
  • NSKernAttributeName: Quy định khoảng cách (số point) giữa các characters. Default là 0: no kerning.
NSKernAttributeName: 10

  • NSStrikethroughStyleAttributeName and NSUnderlineStyleAttributeName: strikethrough và underline cho text với nhiều styles khác nhau. Default là none.
    • strikethrough styles (sử dung enum .rawValue): + NSUnderlineStyle.StyleNone + NSUnderlineStyle.StyleSingle + NSUnderlineStyle.StyleThick + NSUnderlineStyle.StyleDouble
    • Strikethrough patterns (to be OR-ed with the style): + NSUnderlineStyle.PatternDot + NSUnderlineStyle.PatternDash + NSUnderlineStyle.PatternDashDot + NSUnderlineStyle.PatternDashDotDot
    • Chỉ apply cho từng words (not spaces): + NSUnderlineStyle.ByWord
NSStrikethroughStyleAttributeName: NSNumber(integerLiteral:NSUnderlineStyle.styleSingle.rawValue)

NSUnderlineStyleAttributeName: NSNumber(integerLiteral:NSUnderlineStyle.styleSingle.rawValue)

  • NSStrokeColorAttributeName: outline color của text
  • NSStrokeWidthAttributeName: đặc trưng cho stroke width. Default là 0. Nếu value có giá trị dương thì sẽ chỉ thay đổi stroke width. Nếu value có giá trị âm sẽ stroke và fill text.
NSStrokeColorAttributeName: UIColor.blue,
NSStrokeWidthAttributeName: 2

  • NSShadowAttributeName: đỗ bóng cho text. Default là no shadow.
  • NSTextEffectAttributeName: Sử dụng thuộc tính này để chỉ định một hiệu ứng văn bản. Default là nil (không có text effect).
  • NSAttachmentAttributeName: Giá trị của thuộc tính này là một đối tượng NSTextAttachment. Default là nil (không có tệp đính kèm).
  • NSLinkAttributeName: Giá trị của thuộc tính này là đối tượng NSURL và NSString. Default là nil (không có link liên kết)
  • NSBaselineOffsetAttributeName: mô tả character’s offset from the baseline.
let aString = NSMutableAttributedString(string: "NSAttributedString")
aString.addAttributes([NSBaselineOffsetAttributeName:5], range: NSRange(location: 2, length: 10))

  • NSUnderlineColorAttributeName: Color của underline text
  • NSStrikethroughColorAttributeName: Color của strikethrough
  • NSObliquenessAttributeName: set thuộc tính nghiêng cho text. Default là 0 (không nghiêng), giá trị dương -> nghiêng về bên phải, giá trị âm -> nghiêng về bên trái.
NSObliquenessAttributeName: 1
NSObliquenessAttributeName: -1

  • NSExpansionAttributeName: Thuộc tính mở rộng cho text. Default là 0 (không mở rộng)
NSExpansionAttributeName: 0
NSExpansionAttributeName: 1

4. Một số hạn chế của NSAttributedString:

  • Nếu hiển thị text theo chiều dọc, thì atttributed string không được apply.
  • Nếu muốn draw theo 1 hình khác (không phải thì chữ nhật) thì phải dùng CoreText
  • Nếu muốn render text không theo hàng ngang (nhưng hình cong,...) thì phải dùng CoreText và CATextLayer.

5. Kết luận:

Trên đây mình giới thiệu tổng quát về NSAttributedString, với các character attributed cơ bản, hay sử dụng. Hy vọng bài viết giúp ích cho các bạn để làm app của mình thêm sinh động hơn với những đoạn text thú vị và đẹp mắt. Thanks.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí