From 7321427980ebede33cff61d0ae8c89fa6ebe96bb Mon Sep 17 00:00:00 2001 From: Kevin G Christiano Date: Wed, 4 Dec 2019 15:52:18 -0500 Subject: [PATCH] This needs to be broken down and understood, but the code is here and at least functional. --- MVMCoreUI/Atoms/Views/Label.swift | 61 ++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/MVMCoreUI/Atoms/Views/Label.swift b/MVMCoreUI/Atoms/Views/Label.swift index d677cf4b..544f7666 100644 --- a/MVMCoreUI/Atoms/Views/Label.swift +++ b/MVMCoreUI/Atoms/Views/Label.swift @@ -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.. [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 {