swiftconstraintsuilabelwidthintrinsic-content-size

Obtaining UILabel width when not occupying full screen width?


I would like to obtain the width of a UILabel added as a subView inside a custom TableView Cell. The TableView Class I am using is listed below:

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”)

}

}

However, from the above code when I assigned the rightAnchor constraint for the customLabel UILabel, Xcode did not return the correct width of the UILabel I was looking for.

I understand that I only specified the top and left constraints for the UILabel. I also know that UILabel by default has intrinsic layout on, that it can decide on the required height based on the content of the UILabel. However, I am wondering if I did not set the numberOfLines for the customUILabel defined in the above code as 0 (i.e., I only want my text inside the UILabel to occupy one line only). Can I obtain the width of the customUILabel before the text got truncated.

Let me explain further, if my customLabel has a lot of text, it will occupy the full width of the screen then gets truncated. However, if it does not contain a lot of text, then it’s width will be less than the width of the screen. And this is exactly what I am interested in obtaining, the width of the UILabel used to display the small text inside it?

Regards, Shadi.


Solution

  • You need

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

    Then print the width inside

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

    Don't use frames in constraints calculations

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

    Inside cell init they not yet calculated