Search code examples
iosswiftxcodenslayoutconstraint

constraint LefAnchor constant not updating


I'm trying to update the constant value of the leftAnchor. But it's not working as I hoped it would, it's not updating anything.

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
}

I was hoping the constant of the LeftAnchor would be updated, except it isn't. If I print the X value, it returns with a proper value tho.


Solution

  • Update, this works.

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