简体   繁体   中英

Unable to programmatically set UIButton action

I'm having a bit of trouble with the action on my UIButtons. I'm creating 4 buttons programmatically but I'm not able to get the TouchUpInside event to fire.

I've had a read through SO but I'm still having trouble so any pointers will be greatly appreciated!

Here's the code where I create and set the button and it's action:

UIButton *btn;

float newWidth = 10;

for (int i = 0; i < _btnImages.count; ++i) {
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect imageFrame = CGRectMake(/*X*/newWidth, /*Y*/height - 80, 65, 65);
    btn.frame = imageFrame;
    btn.tag = i;

    [btn setBackgroundImage:[UIImage imageNamed:[_btnImages objectAtIndex:i]] forState:UIControlStateNormal];
    [btn addTarget:self
            action:@selector(btnSelected:)
            forControlEvents:UIControlEventTouchUpInside];
    [btn setEnabled:true];

    [self addSubview:btn];
    newWidth = newWidth + 75;
}

and here is the btnSelected method:

-(void)btnSelected:(UIButton *)button
{
    NSLog(@"Button %ld Clicked",(long int)[button tag]);
} 

The code you have shown is okay. The possible problems are:

  1. You are adding the buttons into a view that has user interaction disabled (or any of its ancestor has user interaction disabled).

  2. Your buttons are clipped by their superview. Make sure your buttons are inside the bounds of their superview (and the superview is inside the bounds of its superview etc.).

  3. Other issues can happen when there are gesture recognizers on your views - they can delay & cancel touches in the subviews, including buttons. Make sure the touch event is not handled by some gesture recognizer.

also UIControlEventTouchUpInside is fired when u release the button from inside the bounds of the button... it can be a little tricky concept but if you press the button, and release from outside the bounds of the button, this control event will not trigger.

UIControlEventTouchUpInside A touch-up event in the control where the finger is inside the bounds of the control. Available in iOS 2.0 and later. Declared in UIControl.h.

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