【发布时间】:2021-01-27 13:36:39
【问题描述】:
我在我的项目中的很多地方都使用这个 UILabel 扩展来填充标签。它在 iOS 13 和更早版本的设备上完美运行。但它在 iOS 14 设备和模拟器上根本不起作用。至少在 iOS 14 上如何解决这个问题?
几年前我从这个答案中找到了这个解决方案: https://stackoverflow.com/a/44145859/7825024
这是我的代码:
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
}
}
【问题讨论】:
标签: ios uilabel padding ios14 uiedgeinsets