Assigning subview to view

I have two custom views in the dock of my view controller. (I linked them up to IBActions already) When button 1 is clicked this code gets triggered:

mainView.addSubview(view1)


So I add view1 as a subview of mainView. (Note: Mainview is a view i created that fills a portion of the screen. Mainview and view1 are the same height and width)


But when I run this view1 is partially off the screen and not where mainView is at all. (No autolayout setup yet)



Thanks for all help!

Replies

How did you define the frame of subview view1 ?

It should be relative to mainView.

How do I define that?

If you're programatically building your view, you are probably already calling init(frame: CGRect). So specify the desired frame there (relative as Claude points out above). i.e. if your parent view has an origin of 100, 100 and you want your child view to be inset from that corner by just 10 points, then set the subview's original to 10, 10 and not 110, 110.


If you're grabbing the subview from a storyboard/nib, initWithCoder will have been called on that view instance at which point the frame is probably set to CGRect.zero. Thus, just set its frame property as needed in something like awakeFromNib or other relevant spot in your code.