Search code examples
c#iosxamarinuitouchtouches

Wait for actions in TouchesEnded to complete before allowing more touch recognition - Xamarin iOS


When a subview is touched it is moved to a specified place in the main view. Only 1 subview should be allowed to move at any given time. Problem is, if I touch two subviews at/nearly the same time (e.g., if user is using both thumbs on mobile device), multiple subviews move at the same time.

I thought if touches == 1, I wouldn't have this problem. I implemented a global bool but that doesn't fix it either.

Any tips? Thanks!

UPDATE I was able to fix half the problem with ExclusiveTouch: when two subviews are touched at the same time, only one moves. BUT, if there is a very short amount of time between the two touches, both subviews still move. Maybe it has to do with the .15-sec animation that moves the tiles? Like one starts before the other finishes?

    ...
    bool canTouch = true;
    ...

            public override void TouchesEnded(NSSet touches, UIEvent evt)
            {
                if (canTouch)
                {
                    canTouch = false;

                    base.TouchesEnded(touches, evt);

                    int touchesCount = (int)touches.Count;

                    if (touchesCount == 1)
                    {
                        UITouch myTouch = (UITouch)touches.AnyObject;
                        UIView touchedView = myTouch.View;

                        // Move 1 touched view...
                        UIView.Animate(.15f,
                                               () => //animation
                                               {
                                                   touchedView.Center = 
                        emptySpot;
                                               },
                                               () => //completion
                                               {
                                                   emptySpot = thisCenter;
                                               });
                            }
                    }

                    canTouch = true;
                }
            }

Solution

  • Have you tried yourView.MultipleTouchEnabled = false;?
    Or disabling it from the View panel of the iOS Designer?

    Update For the fast-touch scenario, I would try to just trap the touch in the "upper" view without additional bool variables around your code.

    public override void TouchesBegan (NSSet touches, UIEvent evt)
    {
        if (! ExclusiveTouch) 
            base.TouchesBegan (touches, evt);
    }
    

    UIViews are derived from UIResponders that forward the event (touch) to the responder chain through base(...)/super(...) in the overridden method. Not executing it for the exclusive view allows you to not forward the touch event.

    Documentation