【发布时间】:2018-12-28 14:54:40
【问题描述】:
我有 2 个简单的 UILabel 需要水平放置。其中一个在视图的右侧,而第二个在左侧并获得所有可能的空间。这是我的限制:
amountOfQuestions.rightAnchor.constraint(equalTo: rightAnchor, constant: -8).isActive = true
amountOfQuestions.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
topicName.leftAnchor.constraint(equalTo: leftAnchor, constant: 8).isActive = true
topicName.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
topicName.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true
topicName.rightAnchor.constraint(equalTo: amountOfQuestions.leftAnchor, constant: -8).isActive = true
看起来一切正常,但是当显示表格视图时,它看起来像这样:
但是在我上下滚动我的表格几次后,它就变得正常了:
为什么我的表格没有像第二张图片那样立即显示?
解决办法:
amountOfQuestions.rightAnchor.constraint(equalTo: rightAnchor, constant: -8).isActive = true
amountOfQuestions.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
amountOfQuestions.setContentHuggingPriority(.required, for: .horizontal)
amountOfQuestions.setContentCompressionResistancePriority(.required, for: .horizontal)
topicName.leftAnchor.constraint(equalTo: leftAnchor, constant: 8).isActive = true
topicName.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
topicName.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true
topicName.rightAnchor.constraint(equalTo: amountOfQuestions.leftAnchor, constant: -8).isActive = true
topicName.setContentHuggingPriority(.required, for: .horizontal)
topicName.setContentCompressionResistancePriority(.required, for: .vertical)
let myBottom = topicName.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8)
myBottom.priority = UILayoutPriority(rawValue: UILayoutPriority.required.rawValue - 1)
myBottom.isActive = true
【问题讨论】:
-
你在哪里设置约束?另请注意,底部约束应将优先级设置为
999(不是必需但高优先级),并且您需要将左侧标签上的垂直拥抱优先级和抗压优先级设置为1000(必需)。并且您必须为正确的标签设置水平拥抱优先级和抗压性。如果你不这样做,那么标签内容将不会被正确考虑。 -
谢谢。我有问题地展示了我是如何设置约束的。但是,为什么需要你告诉的那些限制?他们如何解决问题?为什么不使用它们就无法实现目标?
标签: ios swift uitableview autolayout