Sunday, May 1, 2011

UIButton delayed state change

I have a UIButton subview inside of a UITableViewCell.

When this button is touched, the user must hold the button for about a half second for the button's image to change to the UIControlStateHighlighted image.

This means that if the user just taps the button as is usually the case, the highlighted state is never shown.

Why does this occur and how can I fix it?

From stackoverflow
  • Edit: completely re-written following a misunderstanding of the question

    One way of thinking of a UIButton is as a shorthand way of setting up an area of the screen that can respond to various instantaneous touch events the response it makes is defined by UIControl's Target-Action system for delivering messages to other objects.

    UIControlEventTouchDown sounds like the one you need to respond to. It will be triggered as soon as someone touches inside your button - this is what the "Contact Info" button in SMS does.

    UIButton* myButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect]; // SEt up title, frame etc [myButton addTarget:self action:@selector(myButtonWasPressed) forControlEvents: UIControlEventTouchDown]; [myMainView addSubView:myButton];

    Will send a -(void)myButtonWasPressed message to the object this code runs from (ideally you view controller). In myButtonWasPressed you can then add a new view or take any action you like. The SMS app pushes a view controller to display the contact info using a navigation controller.

    If this still doesn't solve your problem, you're going to have to post some code in order to get more insight into what's going wrong.

  • The problem is that your UIButton is inside a UITableView. This means that the table view has to determine whether your tap is going to be a swipe or if it's just a tap intended for the button. The table view has to delay sending a message to the UIButton until it knows that the user doesn't intend to swipe and therefore scroll the view instead of pressing the button.

    If you don't need a table view, get rid of the UITableView.

  • I just change the image from within the target action method:

    [sender setBackgroundImage:[UIImage imageNamed:@"highlighted-image.png"] forState:UIControlStateNormal];
    

    It changes the background image instantly.

0 comments:

Post a Comment