【问题标题】:Obtaining UILabel width when not occupying full screen width?不占用全屏宽度时获取UILabel宽度?
【发布时间】:2019-07-13 21:40:25
【问题描述】:

我想获取作为子视图添加到自定义 TableView 单元中的 UILabel 的宽度。下面列出了我正在使用的 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 的宽度?

问候, 沙迪。

【问题讨论】:

    标签: swift constraints uilabel width intrinsic-content-size


    【解决方案1】:

    你需要

    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 内还没有计算出来

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2011-11-02
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多