0

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.

enter image description here

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)"
    }
iOSDev2013
  • 67
  • 1
  • 6
  • Easier to answer your question if you explain ***why*** you want to get the width? – DonMag Jan 31 '20 at 14:17
  • Call `super.layoutSubviews()` as first line in your override. – matt Jan 31 '20 at 14:54
  • @matt, tried added super.layoutSubviews() but its stil the same. – iOSDev2013 Feb 02 '20 at 06:32
  • @DonMag, I'm trying to add some subviews to it programmatically, it works fine but has an width issue on initial load due to this issue as initially I'm not getting the correct width – iOSDev2013 Feb 02 '20 at 06:33
  • @iOSDev2013 - let me rephrase... What are you trying to do that you would need absolute width rather than using auto-layout? – DonMag Feb 02 '20 at 14:54

0 Answers0