Add UIView on UIViewController

拟墨画扇 提交于 2019-12-22 10:07:03

问题


I want to add a "custom" uiview onto a uiviewcontroller, this custom view i created with xib and its a seperate from the view controller,

does anyone know how to add a uiview with a xib into a uiviewcontroller?

Many thanks in advance


回答1:


You mean an additional view, not the main controller view? In that case you can declare a property for the view and load the NIB by hand:

@interface Controller {}
@property(retain) IBOutlet UIView *extraView;
@end

…

- (void) viewDidLoad // or anywhere else
{
    [[NSBundle mainBundle] loadNibNamed:@"extras" owner:self options:nil];
    NSAssert(extraView != nil, @"The extra view failed to load.");
    [[self view] addSubview:extraView];
}

This assumes that you set the Controller as the file owner in the Interface Builder and you link the view to the extraView outlet. Also note that there might be more elegant solutions, like inserting the extra view into the main NIB for your controller; depends on the situation.




回答2:


It looks like you want the most common scenario – simply load an intialized custom UIView subclass into a controller.

  1. Create a new XIB, called “View XIB” in the Xcode new file wizard.
  2. In the Interface Builder select the File Owner object and on the Object Identity tab in the Object Inspector (Cmd-4) enter Controller (or however your controller class is named) into the Class field.
  3. Do the same with the view, entering the name of your view class.
  4. Ctrl+drag from the file owner to the view, you should be able to connect the view to the view outlet defined on your controller.
  5. Save, let’s say Controller.xib.
  6. In your code, initialize the controller using initWithNibName:@"Controller" bundle:nil. The initialization code should load the interface for you and set the view property to the view unpacked from the interface file.

Go through some Interface Builder tutorial, IB is a very nice tool and it’s good to be familiar with it.



来源:https://stackoverflow.com/questions/4784285/add-uiview-on-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!