检测长按UINavigationItem的后退按钮

kev*_*boh 14 objective-c uinavigationbar uinavigationcontroller uigesturerecognizer ios

我想通过我的基于UINavigationController的应用程序向我的后退按钮添加功能,其中长按后退按钮将弹出到root.但是,我无法弄清楚手势识别器的附加位置.我是否将UINavigationBar子类化并尝试检测长按是否在左按钮区域?

我之前听说有人添加类似的功能.有人有主意吗?

Rob*_*Rob 18

我知道这个问题很老,但我想出了一个解决方案.我没有尝试将手势识别器添加到按钮本身(这将是理想的),而是将其添加到self.navigationController.navigationBar操作方法中,然后在操作方法中使用locationInView以查看我是否在后退按钮上.我并不完全确定如何准确识别后退按钮,所以我笨拙地抓住第一个子视图,x坐标小于某个任意值,但看起来很有希望.如果有人有更好的方法来识别后退按钮的框架,请告诉我.

- (void)longPress:(UILongPressGestureRecognizer *)sender 
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // set a default rectangle in case we don't find the back button for some reason

        CGRect rect = CGRectMake(0, 0, 100, 40);

        // iterate through the subviews looking for something that looks like it might be the right location to be the back button

        for (UIView *subview in self.navigationController.navigationBar.subviews)
        {
            if (subview.frame.origin.x < 30) 
            {
                rect = subview.frame;
                break;
            }
        }

        // ok, let's get the point of the long press

        CGPoint longPressPoint = [sender locationInView:self.navigationController.navigationBar];

        // if the long press point in the rectangle then do whatever

        if (CGRectContainsPoint(rect, longPressPoint))
            [self doWhatever];
    }
}

- (void)addLongPressGesture
{
    if (NSClassFromString(@"UILongPressGestureRecognizer"))
    {
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [self.navigationController.navigationBar addGestureRecognizer:longPress];
        [longPress release];
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*rew 6

我相信UIGestureRecognizers只能添加到UIViews和UIViews的子类中.

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html

后退按钮是一个UIBarButtonItem,它来自NSObject.因此,您将无法使用手势识别器附加到标准后退按钮

UILongPressGestureRecognizer *longPressGesture =
            [[[UILongPressGestureRecognizer alloc]
              initWithTarget:self action:@selector(longPress:)] autorelease];

[self.navigationItem.backBarButtonItem addGestureRecognizer:longPressGesture];
Run Code Online (Sandbox Code Playgroud)

但是,您可以向UIBarButtonItem添加自定义视图.自定义视图可以很容易地成为UIView,UIButton,UILabel等.

例:

UIView *myTransparentGestureView = [[UIView alloc] initWithFrame:CGRectMake(0,0,40,30)];
[myTransparentGestureView addGestureRecognizer:longPressGesture];
[self.navigationItem.backBarButtonItem setCustomView:myTransparentGestureView];
// Or you could set it like this
// self.navigationItem.backBarButtonItem.customView = myTransparentGestureView;
[myTransparentGestureView release];
Run Code Online (Sandbox Code Playgroud)

但是,您必须小心,因为backBarButtonItem上的设置属性适用于您推送的下一个视图.因此,如果您有视图A推送查看B,并且您希望在视图B中点击时识别手势.您必须在视图A中进行设置.