我正在尝试更新 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 值,它会返回一个正确的值。
最佳答案
更新,这有效。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let x = CGFloat(indexPath.item) * frame.width / 4
horizontalBarLeftAnchorConstraint?.constant = x
collectionView.setNeedsLayout()
}
关于ios - 约束 LefAnchor 常量不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516872/