Search code examples
iosobjective-caddsubview

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.


Solution

  • 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