Joson Daniel
Joson Daniel

Reputation: 409

Recognize click or gesture event on disabled UIButton

My button is disabled but I want to show a message box when user clicks on it. How can I do it? Also I would like to mention that UIbutton is added on UITableview, and I tried the code below, but it always goes to else in DisableClick() function.

In 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];

In 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
    }

}

Upvotes: 4

Views: 1937

Answers (3)

Aqueel
Aqueel

Reputation: 1246

You will need to subclass UIButton and implement touchesBegan:withEvent: and touchesEnded:withEvent: methods for your purpose.

Upvotes: 0

manujmv
manujmv

Reputation: 6445

Why you are initialize a tap gesure for this button. You set the selector in ur addTarget

Maintain a btn boolean for the button status . Change the status whenever you want to disable or enable.

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];

Make the target function as

- (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];
    }

}

Upvotes: 0

Jay Gajjar
Jay Gajjar

Reputation: 2741

Rather than desabling the button keep it enable. Change the image of button like disable image. Put a flag variable when button is tapped use this flag variable to run the code of enabled button and disabled button

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");
   }
}

Upvotes: 2

Related Questions