Swift 計算文字的size

2021-09-11 13:25:45 字數 2612 閱讀 3879

ios 11之前限制寬高計算字串的size用的是uilabeltextrect(forbounds bounds: cgrect, limitedtonumberoflines numberoflines: int) -> cgrect方法,當時也沒考慮執行緒安全問題(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

iflet 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

}}複製**

引數解釋 constrainedsize:限制的size font:字型大小 linespacing:預設為nil,使用系統預設的行間距 lines:限制的行數 注:**版本為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.attributedtext = attributedstring

}}複製**

在此感謝倉鼠:ios 行距全攻略 和github.com/zhengwenmin…

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方法,當時dgsmk也沒考慮執行緒安全問題 low爆了 xcode也沒...