问题
see the attached screenshot , I am seeing an extra padding getting added the top and bottom of the UILabel when the text content is less.
But works as perfectly when dummyDescription Label text is more. Issue is happening only when dummyDescriptionLabel is less.
Below are my constraints which are added progrmatically
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)
])
I have also set below ones still no luck
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
Any help would be greatly appreciated.
回答1:
The content Hugging Priority should be set for vertical constraints. i.e
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
should replaced by:
self.dummyNameLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical)
self.dummyDescriptionLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical)
In this way, the frame of the labels will always be the same as the intrinsic content's height.
Similarly, to prevent the content of the labels from being clipped by their bounds, you can set the vertical compression priority to a default high.
来源:https://stackoverflow.com/questions/56917487/how-to-compress-extra-padding-at-the-top-and-bottom-of-the-uilabel