Reputation: 11
hy,
I'm new in objective-c. I'm trying to add a button into my UIView. But I can't see the button in my application. I tried a lot but nothing worked. I know there are many posts about that but no solution worked at my code.
PinViewController.m:
#import "PinViewController.h"
@implementation PinViewController
@synthesize view,one;
-(instancetype)init{
self = [super init];
if(self){
view = [[UIView alloc] init];
}
return self;
}
-(void)viewDidLoad{
UIButton *btnname = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnname setTitle:@"Click Me" forState:UIControlStateNormal];
btnname.frame = CGRectMake(28, 31, 42, 21);
[self.view addSubview:btnname];
}
PinViewController.h:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface PinViewController : UIViewController
@property(nonatomic, retain) UIView *view;
@property UIButton *one;
@end
In appdeligate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.rootViewController = [[PinViewController alloc]init];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Thank you for your help :)
Upvotes: 0
Views: 273
Reputation: 1239
I take from your question that you specifically want to not have storyboards or xibs. That's a perfectly legitimate but somewhat infrequent choice, and it has it's pros and cons.
You are writing a wrong constructor for PinViewController, which should be a subclass of UIViewController, but it class UIView's constructor instead (which is not its parent).
The other thing is that you shouldn't create (and synthesise) a new property 'view', it is already there for UIViewController, and this way the default setters/getters will be overridden. And you create your new view by setting the property. You'll also have to specify frame otherwise it will have no size. So it is:
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
Third problem is that viewDidLoad was never called. According to documentation at Apple
This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method.
This does not happen since you don't create the view in the loadView method. The loadView method, in turn, is not called at all, because you create the view in the constructor. So the solution is to not override the constructor at all, but do instead:
- (void)loadView
{
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
(Alternatively, you can just call viewDidLoad manually from the constructor after creating the view, which is less nice but does the job)
Upvotes: 1