gpt4 book ai didi

ios - 由于自动布局,在 UILabel 中获取换行符

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:51 30 4
gpt4 key购买 nike

我想获取带有换行符的文本,因为 UILabel 在手机屏幕上使用自动布局显示。谢谢。

例如:如果我分配

label.text = "dhasghdsgah dgahjdg ahjgd hkagkhdhk ajsh djkah"

当它显示在屏幕上时,根据屏幕宽度显示如下:

dhasghdsgah dgahjdg ahjgd

hkagkhdhk ajsh

djkah

我想知道“\n”被自动布局插入到哪里。

如果我遗漏了什么,请纠正我。

请找截图:标签中没有空格。

enter image description here

最佳答案

我用这个方法解决了这个问题:

func getArrayOfStringsOnDifferentLines(label: UILabel) -> [String] {

let text:NSString = label.text! as NSString
let font:UIFont = label.font
let rect:CGRect = label.frame

let myFont:CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attStr:NSMutableAttributedString = NSMutableAttributedString(string: text as String)
attStr.addAttribute(String(kCTFontAttributeName), value:myFont, range: NSMakeRange(0, attStr.length))
let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path:CGMutablePath = CGMutablePath()
path.addRect(CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(rect.size.width), height: CGFloat(100000)), transform: .identity)

let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame) as NSArray
var linesArray = [String]()

for line in lines {
let lineRange = CTLineGetStringRange(line as! CTLine)
let range:NSRange = NSMakeRange(lineRange.location, lineRange.length)
let lineString = text.substring(with: range)
linesArray.append(lineString as String)
}
return linesArray
}

此方法返回位于不同行的字符串数组。现在您可以根据需要使用此数组来创建带有\n 连接的新字符串。

我的用法:

            var stringArray = [String]()

for newItem in self.getLinesArrayOfStringInLabel(label: item.labelToAdd) {
stringArray.append(newItem.replacingOccurrences(of: "\n", with: ""))
}
let stringToSend = stringArray.joined(separator: "\n")
print(stringToSend)

欢迎询问任何细节。谢谢

关于ios - 由于自动布局,在 UILabel 中获取换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427759/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com