约束 LefAnchor 常量不更新

constraint LefAnchor constant not updating

我正在尝试更新 leftAnchor 的常量值。但它没有像我希望的那样工作,它没有更新任何东西。

var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?

func setupHorizontalBar () {

    let horizontalBarView = UIView()
    horizontalBarView.backgroundColor = .yellow

    addSubview(horizontalBarView)
    horizontalBarView.translatesAutoresizingMaskIntoConstraints = false

    horizontalBarLeftAnchorConstraint = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor
        , constant: 0)
    horizontalBarLeftAnchorConstraint?.isActive = true

    horizontalBarView.bottomAnchor.constraint(equalTo:self.bottomAnchor).isActive = true
    horizontalBarView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/4).isActive = true
    horizontalBarView.heightAnchor.constraint(equalToConstant: 4).isActive = true

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let x = CGFloat(indexPath.item) * frame.width / 4
    horizontalBarLeftAnchorConstraint?.constant = x
}

我希望 LeftAnchor 的常量会更新,但事实并非如此。如果我打印 X 值,它 returns 具有适当的值。

更新,这个有效。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let x = CGFloat(indexPath.item) * frame.width / 4
    horizontalBarLeftAnchorConstraint?.constant = x
    collectionView.setNeedsLayout()
}