简体   繁体   English

Swift 约束自动调整标签宽度

[英]Swift constraint autosize label width

This is my code to make UILabel autosize:这是我使 UILabel 自动调整大小的代码:

        gmatesLabel.topAnchor.constraint(equalTo: homeButton.bottomAnchor, constant: 5).isActive = true
        gmatesLabel.trailingAnchor.constraint(equalTo: gmatesUniversitySeparatorView.leadingAnchor, constant: -20).isActive = true
        gmatesLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
//        gmatesLabel.widthAnchor.constraint(equalTo: gmatesLabel.widthAnchor, multiplier: 0.5)
        gmatesLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) 

Also I've tried this code :我也试过这个代码:

gmatesLabel.widthAnchor.constraint(equalTo: gmatesLabel.widthAnchor, multiplier: 0.5, constant: 150).isActive = true

But the problem the labels always shrinked, what did I missed here ?但是标签总是缩小的问题,我在这里错过了什么?

Update I've added the leadingAnchor更新我添加了领先的锚

gmatesLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true

And this the function to set my label :这是设置我的标签的功能:

fileprivate func setCommonGmatesText(_ count: Int ) {

    let commonGmatesString   =  NSMutableAttributedString(string: "\(count)", attributes: [NSFontAttributeName : Font.boldFont22, NSForegroundColorAttributeName: Color.lightGray])
    commonGmatesString.append(NSAttributedString(string: "\(NSLocalizedString("commonGmates", comment: "How much common gmates we got"))", attributes: [NSFontAttributeName : Font.regularFont14, NSForegroundColorAttributeName: Color.lightGray]))
    gmatesLabel.attributedText = commonGmatesString
    gmatesLabel.sizeToFit()
}

在此处输入图片说明

You should set a leadingAnchor to your label (greater or equal to 8pt for instance) so that the label doesn't grow bigger that it's superview.你应该为你的标签设置一个leadingAnchor(例如大于或等于8pt),这样标签就不会变大,成为超级视图。

You should also set the lineBreakMode:您还应该设置 lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM