Chlebta Chlebta - 1 year ago 160
iOS Question

Swift constraint autosize label width

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)

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 ?

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

enter image description here

Answer Source

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.

You should also set the lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download