Swift约束自动标注标签宽度

时间:2017-02-07 09:28:43

标签: 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 = 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()
}

enter image description here

1 个答案:

答案 0 :(得分:1)

你应该为你的标签设置一个leadingAnchor(例如大于或等于8pt),这样标签就不会变得比它的超级视图大。

您还应该设置lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping