利用Swift如何計算文字的size示例詳解

2022-09-20 21:39:12 字數 2447 閱讀 5873

前言

ios 11之前限制寬高計算字串的size用的是uilabel的textrect(forbounds bounds: cgrect, limitedtonumberoflines numberoflines: int) -> cgrect方法,當時dgsmk也沒考慮執行緒安全問題(low爆了),xcode也沒提示,用了好幾個版本,所幸一直都沒問題。

貼下方法(當時為什麼選這個方法就不解釋了):

func textsize(font: uifont, constrainedsize: cgsize, linespacing: cgfloat?, lines: int) -> cgsize

let attributedstring = nsmutableattributedstring(string: self)

let range = nsrange(location: 0, length: attributedstring.length)

attributedstring.addattributes([nsfontattributename: font], range: range)

if linespacing != nil

let calculatedlabel = uilabel()

calculatedlabel.font = font

calculatedlabel.attributedtext = attributedstring

calculatedlabel.numberoflines = lines

let rect = calculatedlabel.textrect(forbounds: cgrect(x: 0, y: 0, width: constrainedsize.width, height: constrainedsize.height), limitedtonumberoflines: lines)

return rect.size

}最近公升級了xcode 9,執行時警告我let calculatedlabel = uilabel()要在主線程執行,這時才意識到問題的嚴重性,馬上進行了修改:

extension string

let rect = attritube.boundingrect(with: constrainedsize, options: [.useslinefragmentorigin, .usesfontleading], context: nil)

var size = rect.size

if let currentlinespacing = linespacing

}return size

} func boundingrect(with constrainedsize: cgsize, font: uifont, linespacing: cgfloat? = nil, lines: int) -> cgsize

let size = boundingrect(with: constrainedsize, font: font, linespacing: linespacing)

if lines == 0

let currentlinespacing = (linespacing == nil) ? (font.lineheight - font.pointsize) : linespacing!

let maximumheight = font.lineheight*cgfloat(lines) + currentlinespacing*cgfloat(lines - 1)

if size.height >= maximumheight

return size

}}引數解釋

注:**版本為swift 4.0

上面的兩個方法分別取代名:方法1和方法2。

方法1:限制寬高,可設定行間距,計算準確

方法2:比方法1多了限制行數功能。

配合使用uilabel的擴充套件方法:

extension uilabel else

}let attributedstring = nsmutableattributedstring(string: normalstring)

let range = nsrange(location: 0, length: attributedstring.length)

attributedstring.addattributes([nsattributedstringkey.font: font], range: range)

attributedstring.addattribute(nsattributedstringkey.paragraphstyle, value: paragraphstyle, range: range)

self.atdgsmktributedtext = attributedstring

}}在此感謝倉鼠: 行距全攻略 和

總結本文標題: 利用swift如何計算文字的size示例詳解

本文位址:

Swift 計算文字的size

ios 11之前限制寬高計算字串的size用的是uilabel的textrect forbounds bounds cgrect,limitedtonumberoflines numberoflines int cgrect方法,當時也沒考慮執行緒安全問題 low爆了 xcode也沒提示,用了好幾個...

Swift 計算文字的size

ios 11之前限制寬高計算字串的size用的是uilabel的textrect forbounds bounds cgrect,limitedtonumberoflines numberoflines int cgrect方法,當時也沒考慮執行緒安全問題 low爆了 xcode也沒提示,用了好幾個...

Swift 計算文字的size

ios 11之前限制寬高計算字串的size用的是uilabel的textrect forbounds bounds cgrect,limitedtonumberoflines numberoflines int cgrect方法,當時也沒考慮執行緒安全問題 low爆了 xcode也沒提示,用了好幾個...