0

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.

  • It pretty much appears (to me) like you've coded things correctly. I'm unsure what you are tying to accomplish, so maybe it deals with involving a `UICollectionView`. The one thing you may have mentioned (or not) - okay, so the `x` value is there, meaning you are hitting things and calculating as wanted. Since you've decided to create `horizontalBarLeftAnchorConstraint` as an optional, is it possible that THAT is the issue? Is it `nil`? –  Oct 01 '17 at 21:16
  • Adding collectionView.setNeedsLayout() worked. – esteemedparomomycin Oct 01 '17 at 21:18
  • 1
    That makes sense. :-) Don't be shy about answering your own question. It may help others with the same issue in the future. –  Oct 01 '17 at 21:20

1 Answers1

0

Update, this works.

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