简体   繁体   中英

Adding UIView subView not working

I have a UIViewController class MyClass that initially had no XIB, and was initialized programmatically. Now, I don't want to load it from an XIB, but I do want to make a small 50x50 UIView (settings overlay view), and I want to add it MyClass , so instead of programatically declaring the new settings overlay view, I thought I would create an XIB file, set the file's owner to MyClass, declare in MyClass.h an IBOutlet UIView *settingsOverlay , and link it in the XIB.

Then in the viewDidLoad method, I do [self.view addSubview:settingsOverlay] , but for some annoying reason it doesn't work. It just doesn't appear. I tried creating a simple UIImageView programmatically and adding it to the subView, and it works just fine, but when done through the XIB, it doesn't work. Can anyone point out what could possible be wrong? Please let me know what other details I might need to include.

If you are trying to add a view using xib then you need to use loadNibNamed method.

[[NSBundle mainBundle] loadNibNamed:@"settingsOverlay" owner:self options:nil];

You can refer developer link for more info - http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/NSBundle_UIKitAdditions/Introduction/Introduction.html

Creating an XIB for the settings overlay view and setting it's owner to MyClass does not implicitly cause that XIB to be loaded as a result of manually instantiating MyClass. You would have to manually load the settings overlay view XIB in MyClass viewDidLoad and add it as a subview. Loading it and passing owner as self will cause it to be bound to the IBOutlet you created, but you still have to add it as a subview.

The code in viewDidLoad would look like this:

[[NSBundle mainBundle] loadNibNamed:@"OverlayView" owner:self];
[self.view addSubview:self.overlayView];

You need to load the MyClass xib before settingsOverlay will be set. Try adding this line before your addSubview call.

[[NSBundle mainBundle] loadNibNamed:@"MyClass" owner:self options:nil];

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