繁体   English   中英

Swift 约束自动调整标签宽度

[英]Swift constraint autosize label width

这是我使 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

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

更新我添加了领先的锚

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

您还应该设置 lineBreakMode:

yourLabel.lineBreakMode = .byWordWrapping

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM