MohamMad Salah
MohamMad Salah

Reputation: 981

Create UIButton inside Objective C method

I am trying to create a UIButton in code, and this code is in some methods which will get called from some class.

Here is the method that creates the button

-(void)createButton
{
    NSLog(@"createButton");
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Get Friends" forState:UIControlStateNormal];
    [button setFrame:CGRectMake(100, 100, 100, 50)];
    [button addTarget:self action:@selector(loadTableView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];    
}

but it never appears in the view, what's wrong?

Edit: if I call this method from viewDidLoad then it works!

Edit 2: the method is in the ViewController class and I call it from MyFacebooDelegate class here is the call code from MyFacebooDelegate class:

 ViewController *m2 = [[ViewController alloc] init];
[m2 createButton];

Upvotes: 0

Views: 589

Answers (2)

ensoreus
ensoreus

Reputation: 69

May be your view is not loaded from Nib yet at the moment. If you created view by instantiating

[[UIViewController alloc] initWithNibName:@"someNibName" bundle:nil];

than view controller will be created and start to load view from Nib asynchronously. So, if UIViewController is instantiated, that does not mean UIView is. So, that's why your button work when created from -viewDidLoad: callback.

Upvotes: 1

Phillip Mills
Phillip Mills

Reputation: 31026

When you create a new ViewController using ViewController *m2 = [[ViewController alloc] init]; it is not the same ViewController that is handling the screen.

Instead of allocating a ViewController, you should be using the one that's created when the application starts.

Upvotes: 1

Related Questions