Swift 如何将UILabel的文本保存在安全区域内?

Swift 如何将UILabel的文本保存在安全区域内?,swift,xcode,uilabel,uiedgeinsets,Swift,Xcode,Uilabel,Uiedgeinsets,我已经创建了一个自定义UILabel,以便能够更改其安全区域,这样文本可以有一些填充,看起来更漂亮,但是在我更改了安全区域后,文本仍然从一条边到另一条边,并且没有添加任何填充。这是我的代码 class customLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) setUp() } required init?(coder aDecoder

我已经创建了一个自定义UILabel,以便能够更改其安全区域,这样文本可以有一些填充,看起来更漂亮,但是在我更改了安全区域后,文本仍然从一条边到另一条边,并且没有添加任何填充。这是我的代码

class customLabel: UILabel {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUp()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    override var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }


    func setUp(){
        lineBreakMode = NSLineBreakMode.byWordWrapping
        numberOfLines = 0
        textColor = UIColor.white
        textAlignment = .center
        layer.cornerRadius = 8
        clipsToBounds = true
        backgroundColor = UIColor.black.withAlphaComponent(0.7)
        font = UIFont.boldSystemFont(ofSize: 20)
        translatesAutoresizingMaskIntoConstraints = false

    }

}
如何将文本保留在新的安全区域插图中


谢谢大家!

安全区域插图不应用于文本填充。添加安全区域是为了防止导航栏、选项卡栏、工具栏等覆盖
UIView
的内容。因此,当您向
UIView
的安全区域添加约束时,可以在
UIView
子类中重写此变量,使其子视图可见。但由于
UILabel
中的文本对安全区域没有约束,因此重写此变量没有任何意义

相反,您需要重写
UILabel
的方法

override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    return bounds.insetBy(dx: 10, dy: 10)
}
insetBy(dx:dy:)
方法从
dx
返回包含左右插入的矩形,从
dy
返回包含顶部和底部插入的矩形