Reputation:
Have an AppDelegate
and a MainViewController
.
In MainViewController
the UIButton
was created, AppDelegate
sets a background image and should show it on MainViewController
. That's pretty much it but I can't see the UIButton
.
Just for alignment purpose I created an IBOutlet
and connected the button in IB.
MainViewController.h
@property (strong, nonatomic) IBOutlet UIButton *searchBtn;
MainViewController.m
@synthesize searchBtn;
AppDelegate.m
@synthesize mainVC;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ViewController > setup:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.mainVC = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
self.window.rootViewController = self.mainVC;
self.window.backgroundColor = [UIColor whiteColor];
// Buttons > Set background images:
[self.mainVC.searchBtn setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
[self.mainVC.view addSubview:self.mainVC.searchBtn];
[self.window makeKeyAndVisible];
return YES;
}
Upvotes: 1
Views: 2128
Reputation: 8608
You should be adding buttons in your MainViewController class, not the AppDelegate first off.
You should also set the background of the view in MainViewController, not the AppDelegate.
It should look like this:
AppDelegate.m
@synthesize mainVC;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ViewController > setup:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.mainVC = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
self.window.rootViewController = self.mainVC;
[self.window makeKeyAndVisible];
return YES;
}
In your MainViewController.m's viewDidLoad put this
- (void)viewDidLoad {
[super viewDidLoad];
// Buttons > Set background images:
[searchBtn setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
//If you adding the button in Interface Builder you don't need to add it again
//[self.view addSubview:self.mainVC.searchBtn];
}
Upvotes: 1
Reputation: 3668
First you don't need IBOutlet
if you are creating it programmatically.
Second you probably want to move the creation of the button in viewDidLoad
of your view controller rather than in your AppDelegate
. It's your view controller's business.
Third you should probably alloc init
your button if you create it programmatically:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(...)];
[button setBackgroundImage:someImage];
[button addTarget:self action:@selector(something:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
something like that.
Upvotes: 6