user214155 user214155 - 1 year ago 81
Objective-C Question

Why UIButton doesn’t appear on the screen?

I create UIButton but it doesn’t appear on the screen.

h

@property (weak, nonatomic) IBOutlet UIButton * button;
@property (weak, nonatomic) IBOutlet UIImage * Image1;


m

_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:@selector(_button1:) forControlEvents:UIControlEventTouchUpInside];
[_button setTitle:@"Show View" forState:UIControlStateNormal];
_button.frame = CGRectMake(0, 0, 437, 765);

_Image1 = [UIImage imageNamed:@"1.png"];
[_button setBackgroundImage:_Image1 forState:UIControlStateNormal];
[self.view addSubview: _button];


Why this button doesn’t work?

But this button work.

UIButton *button1;
button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 addTarget:self action:@selector(swipeleft1:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:@"Show View" forState:UIControlStateNormal];
button1.frame = CGRectMake(0, 0, 437, 765);

UIImage *buttonImage1 = [UIImage imageNamed:@"1.png"];
[button1 setBackgroundImage:buttonImage1 forState:UIControlStateNormal];
[self.view addSubview:button1];

Answer Source

Define your properties this way:

@property (strong, nonatomic) UIButton * button;
@property (strong, nonatomic) UIImage * Image1;

Strong means your button and image will be retained, at the moment they are deallocated before you get a chance to add them to the screen.

IBOutlets can be weak as they are already retained by the view, however you're creating your button programmatically, not using interface builder.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download