Noitidart
Noitidart

Reputation: 37238

UIView get width/height without UIViewController

I have this:

class SheetView: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)

    RCTLogInfo("SHEET VIEW INIT'ED")
    let width = String(format:"%.3f", Double(self.frame.size.width));
    let height = String(format:"%.3f", Double(self.frame.size.height));
    RCTLogInfo("Width: " + width + ", Height: " + height);

  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}

However width and height are always 0. Reading here Access UIView width at runtime it seems I need a viewDidLayoutSubviews but a UIView doesn't seem to have this. I have to use UIViewController to use viewDidLayoutSubviews, however I cannot change from UIView, because the place this component gets used, expects a UIView:

class SheetViewManager : RCTViewManager {

  override func view() -> UIView! {
    return SheetView();
  }

}

Is there anyway to get height/width in just the UIView?

Upvotes: 0

Views: 719

Answers (1)

cloudcal
cloudcal

Reputation: 505

Yes you sure can. Try this . (Swift 3.0)

override func layoutSubviews() {
   super.layoutSubviews()
  print(self.frame)
}

Make sure you know that if your custom view's superview doesn't give your custom view a frame either by frame setting or by autolayout via storyboard or programmatically, your frame will remain at 0 width and 0 height

Upvotes: 1

Related Questions