Reputation: 45
I have a UINavigationController class, I want to add on a button with the method addSubview but its not working
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)];
[self.view addSubview:testbtn];
}
return self;
}
Upvotes: 1
Views: 4304
Reputation: 66242
I assume because you're trying to do this on a navigation controller, you want a bar button item on the toolbar. You need to do this in the UIViewController, not the UINavigationController:
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonSystemItemDone
target:self
action:@selector(buttonPressed:)];
[self.navigationItem setRightBarButtonItem:doneButton];
Also, you should grab a cup of coffee and read through the "overview" section of the UINavigationController class reference. It'll take about 10 minutes and you'll be happy you did.
If I'm wrong, and you do want a UIButton (not a UIBarButtonItem), you also need to do that in a UIViewController subclass. Also, you should use its factory method, not a typical alloc/init:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(20, 90,28,20)
Upvotes: 2
Reputation: 3001
I don't believe you can add a button to a UINavigationController
- it doesn't actually have a view of its own. The UINavigationController
is more of a behind-the-scenes organizer for holding and displaying other UIViewController
s.
You'll need to take your [self.view addSubview:testbtn]
and put that in the code of a UIViewController
, instead of in the code for the UINavigationViewController
. And as David Doyle pointed out in his answer, it's considered better practice to put something like that in viewDidLoad
rather than in initWithNibName
.
Upvotes: 1
Reputation: 1716
If you want to modify a View Controller's view, its not a good idea to do so in the init method. The nib file that extracts the resources that create the View Controller's view takes a small amount of time to complete.
You're better off modifying the View Controller's view by overriding the method -[UIViewController viewDidLoad] like so:
- (void)viewDidLoad
{
UIButton *testbtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 90,28,20)];
[self.view addSubview:testbtn];
}
Upvotes: 0