PanGestureRecognizer的有限区域

时间:2012-05-07 08:57:11

标签: xamarin.ios uipangesturerecognizer

是否可以为PanGestureRecognizer设置边框,以便它只能在有限的区域/视图中平移图像?

非常感谢mutch;)

1 个答案:

答案 0 :(得分:4)

您可以为UIPanGestureRecognizer实现委托方法。检查手势的位置是否在您感兴趣的范围内。对于should *方法,您可以返回false以取消手势。手势启动后,您可以通过将State属性设置为Canceled来取消手势。

public class GestureView: UIView
{
    RectangleF _bounds;

    public GestureView (RectangleF rect) : base (rect)
    {
        this.BackgroundColor = UIColor.Brown;

        UIPanGestureRecognizer pan = new UIPanGestureRecognizer (this, new Selector ("panViewWithGestureRecognizer:"));
        this.AddGestureRecognizer (pan);
        pan.WeakDelegate = this;
        _bounds = new RectangleF (0,0,200, 100);
    }

    [Export("panViewWithGestureRecognizer:")]
    void PanGestureMoveAround (UIPanGestureRecognizer p)
    {
        if (_bounds.Contains (p.LocationInView (this)))
        {
            Console.WriteLine ("PanGestureMoveAround true");
            return;
        }
        Console.WriteLine ("PanGestureMoveAround false");
        p.State = UIGestureRecognizerState.Cancelled;
        return;
    }

    [Export ("gestureRecognizerShouldBegin:")]
    bool ShouldBegin (UIGestureRecognizer recognizer)
    {
        if (_bounds.Contains (recognizer.LocationInView (recognizer.View)))
        {
            Console.WriteLine ("ShouldBegin true");
            return true;
        }
        Console.WriteLine ("ShouldBegin false");
        return false;
    }

    [Export ("gestureRecognizer:shouldReceiveTouch:")]
    public bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch)
    {
        if (_bounds.Contains (touch.LocationInView (recognizer.View)))
        {
            Console.WriteLine ("ShouldReceiveTouch true");
            return true;
        }
        Console.WriteLine ("ShouldReceiveTouch false");
        return false;
    }
}