Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton isn't active

I started to study iOS programming with a book by Aaron Hillegass, and I have found that some samples do not work. Maybe they do not work because there is a new version of iOS and Xcode. Could you explain to me why this code is not working? The button is being created; however, it isn't receiving presses.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     self.window.rootViewController = [[UIViewController alloc] init];
     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     [button setFrame:CGRectMake(10,50,100,10)];
     [button setTitle:@"OK" forState:UIControlStateNormal];
     self.window.backgroundColor = [UIColor whiteColor];
     [self.window addSubview:button];
     [self.window makeKeyAndVisible];

     return YES;
}

Popular advise on such kind of question here is to add

    button.userInteractionEnabled = YES;

but it doesn't help.

Sorry if my question is simple, but I spent several hours to find an answer here and on developer.apple.com.

like image 452
gurk Avatar asked Jun 07 '26 18:06

gurk


2 Answers

For some reason, there is a view on top of the button, which is preventing the button from receiving actions (presses). All you have to do is add:

[self.window bringSubviewToFront:button];

This line of code will put your button on top of the stack of views. Cheers

like image 56
Matthew S. Avatar answered Jun 10 '26 06:06

Matthew S.


try adding these lines

[button addTarget:self action:@selector(hello:) forControlEvents:UIControlEventTouchUpInside];

and this is a method which will be called when button will be clicked

- (void) hello:(id) sender
{


   NSLog(@"helloooo");
}
like image 26
Rahul Patel Avatar answered Jun 10 '26 06:06

Rahul Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!