NSLayout 约束不适用于自定义视图

NSLayout Constraint not working on Custom View

我正在 swift 中创建自定义 UIView,这是自定义视图的代码,

class FormField: UIView {
    
    @IBOutlet var viewLabel : UILabel!
    @IBOutlet var textField: UITextField!
    @IBOutlet var separator: UIView!
    
    private var verticallyCenteredAnchor : NSLayoutConstraint!
    private var topPositionedAnchor : NSLayoutConstraint!
    private var isViewHighlighted = false
    private var view: UIView?
    
    let nibName = "FormField"

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    override class var requiresConstraintBasedLayout: Bool {
        return true
    }
    
    func commonInit() {
        guard let view = loadViewFromNib() else { return }
        self.view = view
        view.frame = self.bounds
        self.addSubview(view)
        
        
        verticallyCenteredAnchor =  viewLabel.centerYAnchor.constraint(equalTo: self.view!.centerYAnchor)
        verticallyCenteredAnchor.isActive = false
        topPositionedAnchor = viewLabel.topAnchor.constraint(equalTo: self.view!.topAnchor,constant: 0)
        topPositionedAnchor.isActive = true
        
        let userNameTap = UITapGestureRecognizer(target: self, action: #selector(animateLabel))
        userNameTap.numberOfTapsRequired = 1
        view.addGestureRecognizer(userNameTap)
    }
    
    @objc func animateLabel() {
        if(self.isViewHighlighted) {
            verticallyCenteredAnchor.isActive = true
            topPositionedAnchor.isActive = false
        } else {
            verticallyCenteredAnchor.isActive = false
            topPositionedAnchor.isActive = true

        }
        self.isViewHighlighted = !self.isViewHighlighted
        UIView.animate(withDuration: 0.5) {
            self.view!.layoutIfNeeded()
        }
    }
    
    func loadViewFromNib() -> UIView? {
        let nib = UINib(nibName: nibName, bundle: nil)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
        }
}

我正在为视图使用 xib 文件,并在其中设置了约束。现在,当有人点击视图时,我正在尝试使用动画更改约束。但这是行不通的,当用户点击视图时,布局不会发生变化。我可以确认当用户点击时调用了 animateLabel() 方法。

现在如果在行中添加,

self.view!.translatesAutoresizingMaskIntoConstraints = false

所有约束都乱七八糟,这不符合我已经在 xib 中设置的约束。

这里出了什么问题?

我正在为视图使用 xib 文件,并且在其中设置了约束。

你在 xib + 代码中的约束有冲突,你需要将 xib 中的约束作为出口挂钩并使用它们 .isActive 属性 并完全删除代码约束