我已经创建了一个自定义的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
}
}
如何将文本保存在新的安全区域内插图?
谢谢您!
最佳答案
safeAreaInsets
不应用于文本填充。添加安全区域是为了防止导航栏、选项卡栏、工具栏等覆盖UIView
的内容,因此可以在UIView
子类中重写此变量,使其子视图在向UIView
的安全区域添加约束时可见。但是由于UILabel
中的文本对安全区域没有约束,因此重写此变量没有任何意义。
相反,您需要重写UILabel
的textRect(forBounds:limitedToNumberOfLines:)方法。
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return bounds.insetBy(dx: 10, dy: 10)
}
insetBy(dx:dy:)
方法返回矩形,其中左、右插入来自dx
,顶部和底部插入来自dy
。关于swift - 如何将UILabel的文本保留在safeArea中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53153179/