I use this UILabel extension for label padding in a lot of areas in my projects. And it works perfectly on iOS 13 and older version devices. But it doesn't work at all on iOS 14 devices and Simulators. How can I solve this problem at least on iOS 14?
I found this solution years ago from this answer: https://stackoverflow.com/a/44145859/7825024
This is my code:
extension UILabel {
private struct AssociatedKeys {
static var padding = UIEdgeInsets()
}
public var padding: UIEdgeInsets? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.padding) as? UIEdgeInsets
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.padding, newValue as UIEdgeInsets?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
override open func draw(_ rect: CGRect) {
if let insets = padding {
self.drawText(in: rect.inset(by: insets))
} else {
self.drawText(in: rect)
}
}
override open var intrinsicContentSize: CGSize {
guard let text = self.text else { return super.intrinsicContentSize }
var contentSize = super.intrinsicContentSize
var textWidth: CGFloat = frame.size.width
var insetsHeight: CGFloat = 0.0
if let insets = padding {
textWidth -= insets.left + insets.right
insetsHeight += insets.top + insets.bottom
}
let newSize = text.boundingRect(with: CGSize(width: textWidth, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: ([.font: self.font ?? UIFont.systemFont(ofSize: 15)]), context: nil)
contentSize.height = ceil(newSize.size.height) + insetsHeight
return contentSize
}
}