This needs to be broken down and understood, but the code is here and at least functional.

This commit is contained in:
Kevin G Christiano 2019-12-04 15:52:18 -05:00
parent 8b0d208047
commit 7321427980

View File

@ -695,7 +695,7 @@ extension Label {
if clauses.isEmpty {
// Replace the last whitespace with \u{00A0} No-break space.
if let start = text?.lastIndex(of: " "), let end = text?.index(after: start) {
text?.replaceSubrange(start..<end, with: "\u{00A0}")
// text?.replaceSubrange(start..<end, with: "\u{00A0}")
}
}
@ -715,6 +715,65 @@ extension Label {
}
}
extension Label {
open func getSeparatedLines() -> [Any] {
if lineBreakMode != .byWordWrapping {
lineBreakMode = .byWordWrapping
}
var lines = [Any]() /* capacity: 10 */
let wordSeparators = CharacterSet.whitespacesAndNewlines
var currentLine: String? = self.text
let textLength: Int = (self.text?.count ?? 0)
var rCurrentLine = NSRange(location: 0, length: textLength)
var rWhitespace = NSRange(location: 0, length: 0)
var rRemainingText = NSRange(location: 0, length: textLength)
var done: Bool = false
while !done {
// determine the next whitespace word separator position
rWhitespace.location = rWhitespace.location + rWhitespace.length
rWhitespace.length = textLength - rWhitespace.location
rWhitespace = (self.text! as NSString).rangeOfCharacter(from: wordSeparators, options: .caseInsensitive, range: rWhitespace)
if rWhitespace.location == NSNotFound {
rWhitespace.location = textLength
done = true
}
let rTest = NSRange(location: rRemainingText.location, length: rWhitespace.location - rRemainingText.location)
let textTest: String = (self.text! as NSString).substring(with: rTest)
let fontAttributes: [String: Any]? = [NSAttributedString.Key.font.rawValue: font]
let maxWidth = (textTest as NSString).size(withAttributes: [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): font]).width
if maxWidth > self.bounds.size.width {
lines.append(currentLine?.trimmingCharacters(in: wordSeparators) ?? "")
rRemainingText.location = rCurrentLine.location + rCurrentLine.length
rRemainingText.length = textLength - rRemainingText.location
continue
}
rCurrentLine = rTest
currentLine = textTest
}
lines.append(currentLine?.trimmingCharacters(in: wordSeparators) ?? "")
return lines
}
open var lastLineWidth: CGFloat {
let lines: [Any] = self.getSeparatedLines()
if !lines.isEmpty {
let lastLine: String = (lines.last as? String)!
let fontAttributes = [NSAttributedString.Key.font.rawValue: font]
return (lastLine as NSString).size(withAttributes: [NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): font]).width
}
return 0
}
}
// MARK: -
extension UITapGestureRecognizer {