我解決使用這種方法此問題:
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)
隨意問任何細節。謝謝
你究竟想要什麼? –
它進入下一行,因爲'UILabel'不適合可用空間中的整個單詞。例如* djkah *根據xcode不適合第二行。 – Rikh
我想要獲取帶有UI –