Align UILabel upper left corner

There is a requirement in the design. The text needs to be displayed in two lines, and the upper left corner is aligned in one line, which is a common requirement.
The old method is generally to calculate the frame size according to the width, and then reset the frame. However, I feel that this method is more troublesome. I thought about whether this can be done through constraints.
I tried it out with this idea, and it works fine. Mainly set three constraints, set the element in the upper left corner, and then call the sizeToFit method after setting the text to solve the problem of inconsistent text width.

insert image description here

The following is the sample code, adding constraints using the framework SnapKit ,

lazy var titleLbl:UILabel = {
    
    
    let _v = UILabel(frame: .zero)
    _v.numberOfLines = 2
    _v.snp.makeConstraints {
    
     make in
        make.top.left.equalToSuperview()
        make.width.lessThanOrEqualToSuperview() // 宽度不能超过父元素,也可以写个数
    }
    return _v
}()

titleLbl.text = "UILabel左上角对齐"
titleLbl.sizeToFit()

But at this time, there is a problem that it seems that some problems have changed the line too early. This problem is actually caused by setting different line break modes. If you think the line break is too early, you can set it as follows.

_v.lineBreakMode = .byCharWrapping

However, I feel that the display of some phrases will not look good in this way, so it is better to use the default line break strategy.

Guess you like

Origin blog.csdn.net/xo19882011/article/details/131700160