How to compress extra padding at the top and bottom of the UILabel

给你一囗甜甜゛ 提交于 2019-12-11 06:34:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!