I'm trying to get the width of one of my subviews inside a UITableview cell. Below is the storyboard layout. Here I'm trying to get the testView width programmatically.
This is my cell class.
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var testView: UIView!
@IBOutlet weak var testLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
print("Width = \(testView.frame.width)")
}
override func layoutSubviews() {
print("Updated Width = \(testView.frame.width)")
testLabel.text = "Testview Frame width is =\(testView.frame.width)"
//Perform calculation based on width
}
}
Here now the problem is I don't get the correct width for the first time, as soon as I perform some operation like clicking on the cell, I get the updated correct width in layoutSubviews. For eg: when I run this on iPhone SE, the expected width is 320 but initially, I'm getting the value set in the storyboard, in this case, it's 414.
Is there any other method in UITableviewCell where I could get the actual width of the view?
Also I'm able to get it to work if I add a timer with 0.1 sec delay, but this seems like a hack, wanted to know if there is any other way.
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.update), userInfo: nil, repeats: false)
@objc func update() {
print("Width = \(testView.frame.width)") //Works fine
testLabel.text = "Testview Frame width is =\(testView.frame.width)"
}