42 lines
1.5 KiB
Swift
42 lines
1.5 KiB
Swift
//
|
|
// UILabel.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 8/4/22.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
|
|
extension UILabel {
|
|
/**
|
|
Provides a text container and layout manager of how the text would appear on screen.
|
|
They are used in tandem to derive low-level TextKit results of the label.
|
|
*/
|
|
public func abstractTextContainer() -> (NSTextContainer, NSLayoutManager, NSTextStorage)? {
|
|
|
|
// Must configure the attributed string to translate what would appear on screen to accurately analyze.
|
|
guard let attributedText = attributedText else { return nil }
|
|
|
|
let paragraph = NSMutableParagraphStyle()
|
|
paragraph.alignment = textAlignment
|
|
|
|
let stagedAttributedString = NSMutableAttributedString(attributedString: attributedText)
|
|
stagedAttributedString.addAttributes([NSAttributedString.Key.paragraphStyle: paragraph], range: NSRange(location: 0, length: attributedText.string.count))
|
|
|
|
let textStorage = NSTextStorage(attributedString: stagedAttributedString)
|
|
let layoutManager = NSLayoutManager()
|
|
let textContainer = NSTextContainer(size: .zero)
|
|
|
|
layoutManager.addTextContainer(textContainer)
|
|
textStorage.addLayoutManager(layoutManager)
|
|
|
|
textContainer.lineFragmentPadding = 0.0
|
|
textContainer.lineBreakMode = lineBreakMode
|
|
textContainer.maximumNumberOfLines = numberOfLines
|
|
textContainer.size = bounds.size
|
|
|
|
return (textContainer, layoutManager, textStorage)
|
|
}
|
|
}
|