Skip to content
This repository has been archived by the owner on Mar 7, 2021. It is now read-only.

Latest commit

 

History

History
37 lines (29 loc) · 1.01 KB

string_builder.md

File metadata and controls

37 lines (29 loc) · 1.01 KB

Building attributed strings

NSAttributedString = text + display rules.

This is very important entity, but the API provided by iOS SDK is not very convenient.

Typical example:

let ps = NSMutableParagraphStyle()
ps.alignment = .center
ps.lineSpacing = 4
ps.lineBreakMode = .byTruncatingMiddle

let s = NSAttributedString(
    string: "some text",
    attributes: [
        .font: UIFont.systemFont(ofSize: 15),
        .foregroundColor: UIColor.black,
        .paragraphStyle: ps
    ]
)

Separation of properties into attributes and paragraph style complicates the creation of NSAttributedStrings.

AttributedStringBuilder solves this problem (available by StringBuilder subspec):

let s = "some text".attributed()
    .font(UIFont.systemFont(ofSize: 15))
    .foregroundColor(UIColor.black)
    .alignment(.center)
    .lineSpacing(4)
    .lineBreakMode(.byTruncatingMiddle)
    .make() // or makeMutable()