【发布时间】:2017-06-07 06:56:24
【问题描述】:
所以我有一个相当简单的单元格视图,我正在尝试自定义它。我有一堆字段和标签,我想如下图所示进行布局
但是我最终使用我设置的约束看起来像这样......
indexLabelBackground(圆圈)
indexLabel(数字)
repsField(REPS左边的0)
repsLabel(REPS 字符串)
dividerLabel(“/”字符串)
weightField(POUNDS 左侧的 0)
weightLabel(磅字符串)
我一遍又一遍地查看我的约束,我找不到任何会让我认为我的约束是错误的,所以我希望一双新的眼睛可以帮助我找出这个令人费解的问题......
P.S.我什至创建了一个新项目并尝试使用故事板重新创建此布局,并使用看起来不错的相同约束。
private func setupViews() {
addSubview(indexLabelBackground)
indexLabelBackground.addSubview(indexLabel)
addSubview(repsField)
addSubview(repsLabel)
addSubview(dividerLabel)
addSubview(weightField)
addSubview(weightLabel)
indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true
indexLabel.centerXAnchor.constraint(equalTo: indexLabelBackground.centerXAnchor).isActive = true
indexLabel.centerYAnchor.constraint(equalTo: indexLabelBackground.centerYAnchor).isActive = true
repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
weightField.leftAnchor.constraint(equalTo: dividerLabel.rightAnchor, constant: 16).isActive = true
weightField.rightAnchor.constraint(equalTo: weightLabel.leftAnchor, constant: -8).isActive = true
weightField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
weightLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true
weightLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
// weightLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true //note this fixes the problem but forces my label to be a fixed width
}
所以要注意的是,如果您查看最后一行,这可以通过一种 hacky 方式“修复”,例如向 weightLabel 添加宽度约束。但是,我想避免这种情况,因为在正确的约束条件下,它看起来很笨拙且没有必要。
【问题讨论】:
-
为什么不使用 Storyboard 呢?
-
如果您要注释图像以表示代码中的哪个视图引用图像中的哪个视图会更有意义。
-
这个项目有几个原因,但是是的......我希望以编程方式完成:(
-
你是对的,对此感到抱歉,进行了编辑
标签: ios swift swift3 autolayout nslayoutconstraint