简体   繁体   English

无法以编程方式设置UIButton操作

[英]Unable to programmatically set UIButton action

I'm having a bit of trouble with the action on my UIButtons. 我在UIButton上的操作遇到了一些麻烦。 I'm creating 4 buttons programmatically but I'm not able to get the TouchUpInside event to fire. 我正在以编程方式创建4个按钮,但无法触发TouchUpInside事件。

I've had a read through SO but I'm still having trouble so any pointers will be greatly appreciated! 我已经读过SO了,但是仍然遇到麻烦,因此任何指针都将不胜感激!

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: 这是btnSelected方法:

-(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 ...这可能是一个棘手的概念,但是如果您按下按钮,然后从按钮范围之外释放,则不会触发此控件事件。

UIControlEventTouchUpInside A touch-up event in the control where the finger is inside the bounds of the control. UIControlEventTouchUpInside控件中的修饰事件,手指在控件的边界内。 Available in iOS 2.0 and later. 在iOS 2.0及更高版本中可用。 Declared in UIControl.h. 在UIControl.h中声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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