[英]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.