簡體   English   中英

在不占據全屏寬度的情況下獲取UILabel寬度?

[英]Obtaining UILabel width when not occupying full screen width?

我想獲得UILabel的寬度,該UILabel作為子View添加到自定義TableView Cell中。 下面列出了我正在使用的TableView類:

import UIKit

class customTableViewCell: UITableViewCell {

let customLabel: UILabel = {

 let label = UILabel()
 label.translateAutoConstraints = false
 label.textAlignment = .left
 return label

}()

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

 super.init(style: style, reuseIdentifier: reuseIdentifier)

 contentView.addSubview(customLabel)

 customLabel.topAnchor.constraint(equal: contentView.topAnchor).isActive = true

 customLabel.leftAnchor.constraint(equal: contentView.leftAnchor, constant: 10).isActive = true

 customLabel.rightAnchor.constraint(equal: contentView.rightAnchor, constant: (contentView.frame.size.width/2)-10-customLabel.frame.size.width).isActive = true

}

required init?(coder aDecoder: NSCoder) {

 fatalError(“init(coder:) has not been implemented”)

}

}

但是,從上面的代碼中,當我為customLabel UILabel分配了rightAnchor約束時,Xcode並未返回我正在尋找的UILabel的正確寬度。

我了解我只為UILabel指定了頂部和左側約束。 我也知道UILabel默認具有固有的布局,它可以根據UILabel的內容確定所需的高度。 但是,我想知道是否沒有將上述代碼中定義的customUILabel的numberOfLines設置為0(即,我只希望UILabel中的文本僅占據一行)。 我可以在截斷文本之前獲取customUILabel的寬度嗎?

讓我進一步解釋一下,如果我的customLabel有很多文本,它將占據屏幕的整個寬度,然后被截斷。 但是,如果它不包含很多文本,則它的寬度將小於屏幕的寬度。 這正是我有興趣獲得的,用於在其中顯示小文本的UILabel的寬度嗎?

問候,沙迪。

你需要

self.contentView.rightAnchor.constraintGreaterThanOrEqualToAnchor(customLabel.rightAnchor, constant: 8.0).active = true

然后在里面打印寬度

override func layoutSubviews() {
   super.layoutSubviews()
   print(customLabel.frame.width)
}

不要在約束計算中使用框架

(contentView.frame.size.width/2)-10-customLabel.frame.size.width

內部單元init尚未計算

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM