ios - 约束 LefAnchor 常量不更新

标签 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 值,它会返回一个正确的值。

最佳答案

更新,这有效。

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/

相关文章:

iphone - iOS - UITableView 滚动条超出屏幕

ios - 我怎样才能用 Swift 编程渐变边框颜色 UIButton

xcode - 如何在 iOS 上调整位图的大小

ios - 如何快速将 UIImage 传递给 iOS 中的 Today Extension?

ruby-on-rails - 当安装了 Xcode 4.3.2 并且缺少 gcc 时,如何使用 RVM 安装 Ruby 1.9.3?

带有 c 数组数组的 Objective-C malloc

objective-c - 如何在不进入编辑模式的情况下直接编辑UITableView中的一行

swift - 定义与以前的值冲突 - 另外,何时删除覆盖?

objective-c - 如何使用 AnyClass 对象中定义的类型在 Swift 中声明变量?

ios - 如何在 iOS 应用程序中获取翻译数据库