简体   繁体   中英

UIView loaded from xib as subview : How to set the frame/size properly?

I have a small problem with my iphone app (I am quite new to iphone programmation even if I had already done objective-c before).

I have an UIView named centerView in my main window. I have created a singleton subclass of UIViewController (let's call it FooViewController ) linked with a xib file. My goal is to load the associated view as a subview (of centerView using the whole frame of centerView).

Problem: The view controlled by FooViewController does not use the frame of its superview.

I have tried to add:

  • self.view.frame = self.view.superview.frame in the "custom initialisation" part of the initWithNib... method of FooViewController

  • [[[FooViewController sharedController] view] setFrame:centerView.frame] when I add the view to centerview ( [centerView addSubView:[[FooViewController sharedController] view]] ) (I have tried before and after this line)

But I can't get the good behavior (ie the good size). There are multiple questions related to this kind of problems but I was unable to find my answer in them so:

  • Do you know how I can solve that?
  • [optional] How did the instanciation of a UIViewController linked with a xib works? There must be a resource file where the name of the xib is indicated? Or maybe does it looks for a xib with the same name as the class?

Thanks in advance for your help.

When loading from a NIB, a view is loaded in the view controller's loadView method, not in the initializer. Since you shouldn't really override loadView , esp. if you are loading it from a NIB, you should try doing #1 ( self.view.frame = self.view.superview.frame ) in the view controller's viewDidLoad method. Of course, you should ensure that the view is added to a superview by the time you execute this statement. You also need to make sure that the superview's frame has been correctly set by this time.

Another place where you can try this is in the viewWillAppear: method. Most probably your view's super view will have been set up properly by then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM