Swift 更改约束的乘数值
我有一个菜单栏,它位于CollectionViewController的顶部,有几个不同的标题,大约30像素高 . 每个标题下面都有一个小条,指示用户所在的页面/项目,类似于Youtube应用程序Swift 更改约束的乘数值,swift,Swift,我有一个菜单栏,它位于CollectionViewController的顶部,有几个不同的标题,大约30像素高 . 每个标题下面都有一个小条,指示用户所在的页面/项目,类似于Youtube应用程序 class MenuBar : UIView { var menuSectionTitles = ["Title1","Title2", "Title3","Title4"] var numberOfSectionsInHorizontalBar : CGFloat? var horizonta
class MenuBar : UIView {
var menuSectionTitles = ["Title1","Title2", "Title3","Title4"]
var numberOfSectionsInHorizontalBar : CGFloat?
var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?
var horizontalBarWidthAnchorConstraint: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
setupHorizontalBar()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupHorizontalBar() {
let horizontalBarView = UIView()
horizontalBarView.backgroundColor = UIColor.rgb(10, green: 150, blue: 255)
horizontalBarView.translatesAutoresizingMaskIntoConstraints = false
addSubview(horizontalBarView)
horizontalBarLeftAnchorConstraint = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor)
horizontalBarLeftAnchorConstraint?.isActive = true
horizontalBarView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
// Set the multiplier/width of the horizontal bar to indicate which page the user is on
horizontalBarWidthAnchorConstraint = horizontalBarView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1 / 4)
horizontalBarWidthAnchorConstraint?.isActive = true
horizontalBarView.heightAnchor.constraint(equalToConstant: 3).isActive = true
}
}
horizontalBarWidthAnchorConstraint
的乘数值以1/4的值进行硬编码
我希望在不同的视图控制器之间多次重用视图,因此尝试更改水平BarWidthAnchorConstraint
的乘数,如下所示:
class ViewController: UICollectionViewController {
lazy var menuBar : MenuBar = {
let mb = OptionsBar()
mb.menuOptions = ["Title1", "Title2", "Title3"]
mb.translatesAutoresizingMaskIntoConstraints = false
mb.horizontalBarWidthAnchorConstraint?.constant = 1/3
return mb
}()
}
但这种方法不起作用。我找不到从ViewController内部更改乘数值的方法。在这里的代码中,您正在更改约束的
常量,而不是乘数。对吗
还要注意,约束的乘数
是只读的。你不能改变它。如果要更改应用于视图的约束的
乘数
,则只需使用新乘数添加新约束并删除旧约束即可
读/写约束的唯一部分是
常量
属性。是有意义的,可以从中得出完整的答案:)如果可以,请确保我对答案的编辑是正确的,我会将答案标记为正确的