Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton that will ignore a 'drag' and pass it to UIScrollView

I know there are similar posts on Stack but nothing that I've found has helped me find a solution.

  • I have a scrollview added to a UIView.
  • I have added a UIButton to the same UIView above the scrollview.

    1. I want the UIButton to respond to a touchUp and fire an event.
    2. If someone DRAGS on the UIButton I want it to pass the event to the scrollView and drag the UIScrollView without firing the button event.

I know how to pass on a touch with hitTest returning the scrollview but this stops anything getting to the UIButton.

I don't want to add the UIButton to the UIScrollView.

Does anyone have a proposed solution?

like image 762
Morgz Avatar asked May 13 '11 10:05

Morgz


1 Answers

As explained in this answer, a UIButton or other UIControl that is a subview of a scroll view will automatically respond to taps while letting the scroll view handle drags. However, buttons that are subviews of the scroll view will also move with the scrolled content, rather than remaining in the same position on the screen as the content scrolls beneath them. I assume this is why you don't want to put the buttons into the scroll view.

If that's the case, you can get the desired behavior with one more step. Put all your buttons into a UIView that is a subview of the scroll view, then in the scrollViewDidScroll method of the scroll view's delegate, set that view's frame.origin to the scroll view's contentOffset. I just implemented this in my app and it's working great, without having to do any subclassing or get involved with the responder chain or touch events.

like image 151
arlomedia Avatar answered Sep 22 '22 07:09

arlomedia