简体   繁体   中英

UIButton - addTarget not working

Adding a button to the bottom right of the screen:

    UIButton *testBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [testBtn addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;

    testBtn.frame = CGRectMake(screenWidth - 100, screenHeight - 100, 100, 100);

    [self.view addSubview:testBtn];

I can see the button, and tapping it turns it blue momentarily. It just doesn't call the test: method. Why not?

EDIT - here's the target method:

- (void)test:(id)sender {
    NSLog(@"hi");
}

Could it be because your selector is test: instead of just test? Also, you called it lockBtn, but you used btn to reference the method call...you are referencing a different button maybe?

  1. Your instance is called lockBtn but you are adding a target to btn .
  2. Your method signature may be @selector(test) and not @selector(test:) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM