Swift约束自动调整标签宽度

这是我的代码,使UILabel自动resize:

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 

但标签总是缩小的问题,我在这里错过了什么?

更新我添加了leadingAnchor

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

这是设置我的标签的function:

 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),这样标签就不会变得比它的超级视图大。

您还应该设置lineBreakMode:

 yourLabel.lineBreakMode = .byWordWrapping