约束LefAnchor常量不更新

时间:2017-10-01 21:03:14

标签: ios swift xcode nslayoutconstraint

我试图更新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值,它将以适当的值返回。

1 个答案:

答案 0 :(得分:0)

更新,这有效。

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