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