- 變態(tài)需求要根據(jù)屏幕寬度谈秫,first name長(zhǎng)度不確定
- first name較短
- 若 Good morning, first name,1行能顯示下, 用 Good morning, first name
- 若 Good morning, first name,1行不能顯示下:若Hi, first name 能顯示下鱼鼓,則用Hi否則考慮兩行的情況拟烫。
兩行情況同上,但是換行的時(shí)候得在第一行的末尾加 -
- first name特別長(zhǎng)
- 用Hi,且末尾得加上 ...
- 先上代碼吧
// 1.初始化路徑
let path = CGPath(rect: self.bounds, transform: nil)
// 2.初始化framesetter
let framesetter = CTFramesetterCreateWithAttributedString(text)
// 3.繪制frame
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, text.length), path, nil)
self.ctframe = frame
// 獲得CTLine數(shù)組
let lines = CTFrameGetLines(frame)
// 獲得行數(shù)
let numberOfLines = CFArrayGetCount(lines)
// 獲得每一行的origin, CoreText的origin是在字形的baseLine處的
var lineOrigins = [CGPoint](repeating: CGPoint(x: 0, y: 0), count: numberOfLines)
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), &lineOrigins)
// 遍歷每一行
for index in 0..<numberOfLines {
let origin = lineOrigins[index]
let line = unsafeBitCast(CFArrayGetValueAtIndex(lines, index), to: CTLine.self)
let lineRef: CTLine = line
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range: NSRange = NSMakeRange(lineRange.location, lineRange.length)
let lineString = (attributedText?.attributedSubstring(from: range)).string
}
這樣就得到了每一行的characters
重要的是這個(gè)是利用CoreText 的富文本屬性去做的迄本,一定要是這個(gè)Label的NSMutableAttributedString, 然后把得到的string轉(zhuǎn)成 AttributedString硕淑,給label的富文本屬性,這樣才正確嘉赎。
- 富文本屬性簡(jiǎn)單用法舉例:
let font = UIFont.boldSystemFont(ofSize: 20)
let attributedText = NSMutableAttributedString(string: content)
// 字體顏色
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0, attributedText.length))
// 字體
attributedText.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, attributedText.length))
// 段落樣式
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byCharWrapping
// 行間距
paragraphStyle.lineSpacing = 5.0
// 字符間距
paragraphStyle.paragraphSpacing = 2.0
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length))
label.attributedText = attributedText