我想为UILabel添加约束我的自定义UIView类:
class LabelView: UIView {
public var label: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = frame
prepareUI()
}
func prepareUI() {
self.label.text = "SOME TEXT"
self.label.sizeToFit()
self.label.adjustsFontSizeToFitWidth = true
self.label.textAlignment = .center
self.addSubview(self.label)
self.translatesAutoresizingMaskIntoConstraints = false
self.label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.label.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.5).isActive = true
self.label.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.2).isActive = true
}
}
运行后,我得到以下错误,UILabel位于UIView的左上角:
2021-02-13 02:32:26.698694 1000 SwiftHello[96793:1625524][LayoutConstraints]无法同时满足约束。可能以下列表中至少有一个约束是您不想要的。试着这样做:(1)看看每个约束条件,找出你不期望的;(2) 找到添加了一个或多个不需要的约束的代码,并将其修复。(注意:如果您看到的是您不理解的NSAutoresizingMaskLayoutConstraints,请参阅UIView属性translatesAutoresizginMaskIntoConstraints的文档)(“
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraint 处创建一个符号断点,以便在调试器中捕获此断点。UIView 上 UIConstraintBasedLayoutDebugging 类别中列出的方法列在
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraint 处创建一个符号断点,以便在调试器中捕获此断点。UIView 上 UIConstraintBasedLayoutDebugging 类别中列出的方法列在
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraint 处创建一个符号断点,以便在调试器中捕获此断点。UIView 上 UIConstraintBasedLayoutDebugging 类别中列出的方法列在
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraint 处创建一个符号断点,以便在调试器中捕获此断点。UIView 上 UIConstraintBasedLayoutDebugging 类别中列出的方法列在
你错过了这一行:
self.label.translatesAutoresizingMaskIntoConstraints = false
你把它设置在自己身上,而不是标签上。