本文介绍了Swift约束自动调整标签宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使UILabel自动调整大小的代码:

This is my code to make UILabel autosize:

        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)

我也尝试过以下代码:

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 ?

更新我已经添加了leadAnchor

UpdateI'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()
}

推荐答案

您应该在标签上设置一个LeadingAnchor(例如,大于或等于8pt),以使标签不会变得比其父视图大.

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.

您还应该设置lineBreakMode:

You should also set the lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping

这篇关于Swift约束自动调整标签宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 15:14