识别禁用的UIButton上的点击或手势事件

时间:2013-10-04 04:22:16

标签: ios objective-c uibutton uitapgesturerecognizer

我的按钮已停用,但我想在用户点击时显示一个消息框。我该怎么做?另外我想提一下在UITableview上添加了UI按钮,我尝试了下面的代码,但它总是转到else函数中的DisableClick()

cellForRowAtIndexPath:

button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(180, 6, 30, 30)];
    [button setTag:4000];
    [button addTarget:self action:@selector(click:event:) forControlEvents:UIControlEventTouchDown];
    UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DisableClick:)];
    [self.view addGestureRecognizer:gesture];
    [gesture release];
    [cell.contentView addSubview:button];

DisableClick()

- (void)DisableClick:(UIButton*)sender {
    UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
    CGPoint pt = [recognizer locationOfTouch:0 inView:market];
    if (CGRectContainsPoint(market.bounds, pt)) {
        NSLog(@"Disabled button tapped");

    }
    else 
    {
     NSLog(@"go out"); // it's always go to here
    }

}

3 个答案:

答案 0 :(得分:2)

不是禁用按钮而是启用它。更改按钮的图像,如禁用图像。点击按钮时放置一个标志变量使用此标志变量来运行启用按钮和禁用按钮的代码

BOOL btnFlg;//initialize it true or false on cellForRowAtIndex... method
- (void)DisableClick:(UIButton*)sender 
{
   if(btnFlg)
   {
           btnFlag=NO;
           NSLog("button disabled");
   }
   else
   {
          btnFlag=YES;
          NSLog("button enabled");
   }
}

答案 1 :(得分:0)

为什么要为此按钮初始化tap gesure。您可以在 addTarget

中设置选择器

为按钮状态保持btn布尔值。无论何时要禁用或启用,都要更改状态。

  

BOOL btnEnabled;

 button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(180, 6, 30, 30)];
    [button setTag:4000];
    [button addTarget:self action:@selector(DisableClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button];

将目标函数设为

- (void)DisableClick:(UIButton*)sender {

    //set the function that you needed when the user tap on this button here.
    if(btnEnabled)  {
     // here invoke the functions you needed when the button enabled
    } else {
       UIAlertView *msg = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Your button is disabled" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
       [msg show];
    }

}

答案 2 :(得分:0)

您需要子类化UIButton并实现 touchesBegan:withEvent:和touchesEnded:withEvent:方法用于你的目的。