Ios 快速约束自动调整标签宽度

Ios 快速约束自动调整标签宽度,ios,swift,cocoa-touch,autolayout,constraints,Ios,Swift,Cocoa Touch,Autolayout,Constraints,这是使UILabel自动调整大小的代码: gmatesLabel.topAnchor.constraint(equalTo: homeButton.bottomAnchor, constant: 5).isActive = true gmatesLabel.trailingAnchor.constraint(equalTo: gmatesUniversitySeparatorView.leadingAnchor, constant: -20).isActive =

这是使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) 
我还尝试了以下代码:

gmatesLabel.widthAnchor.constraint(equalTo: gmatesLabel.widthAnchor, multiplier: 0.5, constant: 150).isActive = true
但问题是标签总是缩水,我错过了什么

更新 我已经添加了leadingAnchor

gmatesLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
此函数用于设置我的标签:

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),这样标签就不会比superview更大

还应设置lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping

为什么没有主播?例如,您可以定义一个前导锚点并将其定义为大于5。如果需要,标签将增长到该大小,如果没有(因为文本不够长),它将正好适合text@Ocunidee我没有添加
leadingAnchor
,因为我的视图将被压缩
右上
,定义
高度宽度
就足够了,无需添加其他约束。以这种方式使用故事板效果很好,但在编程上我不知道为什么它不起作用!在这里,您需要调整宽度大小,这样您就不能设置宽度,只能设置高度。为了确保标签不会大于它的superview,应该设置一个等于或大于8pt(通常边距大小)的前导锚定。您的标签将调整大小。也许一张截图能帮助你看清你的真实想法problem@Ocunidee我已经添加了主播,但总是得到相同的结果检查我的更新我可以想到几件事:你在标签中的哪里添加文本?在向其中添加文本后,您应该执行yourLabel.sizeToFit()操作,还应该定义lineBreakMode:yourLabel.lineBreakMode=.byWordWrapping