请参阅所附的屏幕截图,当文本内容较少时,我看到在UILabel的顶部和底部添加了额外的填充。
但是当dummyDescription Label文本更多时,效果很好。仅当dummyDescriptionLabel较小时才会发生问题。
下面是我的约束,这些约束是通过编程方式添加的
NSLayoutConstraint.activate([
self.dummyImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 24),
self.dummyImageView.topAnchor.constraint(equalTo: self.topAnchor,constant:24),
self.dummyImageView.widthAnchor.constraint(equalToConstant: 105),
self.dummyImageView.heightAnchor.constraint(equalToConstant: 67),
self.dummyNameLabel.topAnchor.constraint(equalTo: self.dummyImageView.topAnchor),
self.dummyNameLabel.leadingAnchor.constraint(equalTo: self.dummyImageView.trailingAnchor, constant: 16),
self.dummyNameLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -24),
self.dummyDescriptionLabel.topAnchor.constraint(equalTo: self.dummyImageView.bottomAnchor, constant: 16),
self.dummyDescriptionLabel.leadingAnchor.constraint(equalTo: self.dummyImageView.leadingAnchor),
self.dummyDescriptionLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -24),
self.dummyButton.topAnchor.constraint(equalTo: self.dummyDescriptionLabel.bottomAnchor, constant: 5),
self.dummyButton.leadingAnchor.constraint(equalTo: self.dummyImageImageView.leadingAnchor),
self.readMoreButton.heightAnchor.constraint(equalToConstant: 20)
])
我还在下面设置了仍然没有运气的
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
任何帮助将不胜感激。
答案 0 :(得分:0)
应该为垂直约束设置内容拥抱优先级。即
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
应替换为:
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical)
这样,标签的框架将始终与内部内容的高度相同。
类似地,为防止标签内容被其边界限制,您可以将垂直压缩优先级设置为默认值高。