我已经创建了一个自定义UILabel以便能够更改其安全区域,以便文本可以有一些填充并看起来更好,但是在更改了safeArea之后,文本仍然从边缘到边缘一直沿行,并且此处未添加填充我的代码
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
}
}
如何将文本保留在新的safeAreaInset中?
谢谢!
safeAreaInsets
不应用于文本填充。添加了UIView
“安全区域”以防止导航栏,标签栏,工具栏等覆盖内容。因此,UIView
当您向UIView
“安全区域”添加约束时,您可以在子类中覆盖此变量以使其子视图可见。但是由于文本中UILabel
没有对“安全区域”的限制,所以覆盖此变量没有任何意义。
相反,您需要重写的textRect(forBounds:limitedToNumberOfLines :)方法UILabel
。
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return bounds.insetBy(dx: 10, dy: 10)
}
insetBy(dx:dy:)
方法返回具有的左和右插图dx
以及的上和下插图的矩形dy
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句