【问题标题】:iOS 14 and Simulator UILabel extension padding bugiOS 14 和模拟器 UILabel 扩展填充错误
【发布时间】: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


    【解决方案1】:

    很奇怪,但我找到了解决方案。当 Xcode 12 确实取消选择“调试可执行文件”时,此代码适用于 Simulator 和 iOS 14 设备。

    在 Xcode 12 中,我取消选择“调试可执行文件”部分,因为有时编译需要很长时间。这样我就注意到我的填充代码正在工作。这很有趣,但现在,我会在发布应用程序时使用它。

    解决办法是取消选择这个:

    产品 -> 方案 -> 编辑方案 ... -> 运行 -> 信息 -> 调试 可执行文件

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2016-12-26
      • 2020-04-25
      相关资源
      最近更新 更多