所以我对我创建的视图有一个非常简单的布局,基本上我想要它添加约束后的样子如下所示,
然而,我最终得到的是其他东西,我不知道为什么会发生这种情况。
所以,只是简单地了解我为了实现我想要的布局而做了些什么。
private func setupDividerLabelLayout() {
addSubview(dividerLabel)
dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
private func setupIndexLabelBackgroundLayout() {
addSubview(indexLabelBackground)
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
}
private func setupRepsLabelLayout() {
addSubview(repsLabel)
repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
private func setupRepsFieldLayout() {
addSubview(repsField)
repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
}
答案 0 :(得分:0)
为了让你能够稳定工作,你应该添加_ViewName_.translatesAutoresizingMaskIntoConstraints = false
。
所以代码如下:使用代码
private func setupDividerLabelLayout() {
addSubview(dividerLabel)
dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
dividerLabel.translatesAutoresizingMaskIntoConstraints = false
}
private func setupIndexLabelBackgroundLayout() {
addSubview(indexLabelBackground)
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
indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false
}
private func setupRepsLabelLayout() {
addSubview(repsLabel)
repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
repsLabel.translatesAutoresizingMaskIntoConstraints = false
}
private func setupRepsFieldLayout() {
addSubview(repsField)
repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
repsField.leftAnchor.constraint(equalTo:
indexLabelBackground.rightAnchor, constant: 8).isActive = true
repsField.translatesAutoresizingMaskIntoConstraints = false
indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false
}