0

When adding the code below the subview appears way out of where I intended it to be. It appears almost outside the parent view, and not inside as I expected. I am trying to add the view in viewDidLoad-method.

Parent view bounds:

(0.0, 0.0, 336.0, 200.0)

I am trying to add a view as a subview of this parent:

let subView = UIView(frame: CGRect(x: 200.0, y: 0.0, width: 100.0, height: 20.0))

Answer: How can I get a view's current width and height when using autolayout constraints?

Following the answer fixes the problem without me understanding it fully. Isn't the size of the view updated when laid out by auto layout? Why do I need to invoke this method?

Before I invoke this method the width of the view is 336 points and after I invoke it it is 215 points.

Community
  • 1
  • 1
LuckyLuke
  • 47,771
  • 85
  • 270
  • 434
  • x: 200.0..is exactly "way out of where I intended it to be." – Earl Grey Dec 03 '15 at 11:58
  • I was expecting that x: 200 is somewhere about 2/3 of the width of the parent view, however it is appearing almost at end of the parent view instead only showing about 10 pixels of the subview. – LuckyLuke Dec 03 '15 at 12:00
  • Is it because the width is pixels while the x and y coordinate is points? Do I need to convert the pixel to points? If so, how is the best way to do that? – LuckyLuke Dec 03 '15 at 12:01
  • There is nothing wrong with anything. TBH, It's difficult to even understand your assumptions. The Zero point for the subview is the top left tip of superview. Your subview is 200points to the right with relation to the top left tip of superview. – Earl Grey Dec 03 '15 at 12:07
  • aren't x,y,width and height all in the same unit? – ShahiM Dec 03 '15 at 12:08
  • @EarlGrey Nope, it is not. If it was 200 points from the top left of the superview why am I only seeing about 20 points of it when the superview is 336 points? – LuckyLuke Dec 03 '15 at 13:38
  • You should probably add a screenshot. – Cezar Dec 03 '15 at 13:55
  • @Cezar See updated question. – LuckyLuke Dec 03 '15 at 13:56
  • 1
    336pts in `viewDidLoad` doesn't mean after `viewDidLayoutSubviews` it'll be 336pts again. Do the right stuff in the right place: add subviews in `viewDidLoad`, position them in `viewDidLayoutSubviews`. – Cyrille Dec 03 '15 at 13:58
  • @Cyrille Ok, so should I just add the subview in viewDidLoad with a x:0, y:0 position? And then update it in the viewDidLayoutSubviews? – LuckyLuke Dec 03 '15 at 14:07

0 Answers0