如何根据 UILabel 的宽度拆分字符串。
str = "Here is a sample of a long string that wraps at the end of the screen three times."
width = UIScreen.Main.Bounds.Width
预期结果
strArray = ["Here is a sample of a long", "string that wraps at the end", "of the screen three times."]
看图:
目标是将行提取为字符串,而不是换行。
最佳答案
try below function
func getStringArrayFromLabel(in label: UILabel) -> [String] {
/// An empty string's array
var arrLines = [String]()
guard let text = label.text, let font = label.font else {return arrLines}
let rect = label.frame
let myFont: CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attStr = NSMutableAttributedString(string: text)
attStr.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: myFont, range: NSRange(location: 0, length: attStr.length))
let frameSetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path: CGMutablePath = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000), transform: .identity)
let frame: CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
guard let lines = CTFrameGetLines(frame) as? [Any] else {return arrLines}
for line in lines {
let lineRef = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range = NSRange(location: lineRange.location, length: lineRange.length)
let lineString: String = (text as NSString).substring(with: range)
arrLines.append(lineString)
}
return arrLines
}
关于ios - Swift:给定 UILabel 的宽度拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320095/