设置导航控制器中后退按钮的操作

时间:2009-07-31 21:21:52

标签: ios iphone cocoa-touch uinavigationcontroller uibarbuttonitem

我正在尝试覆盖导航控制器中后退按钮的默认操作。我已经在自定义按钮上提供了一个目标操作。奇怪的是,当通过backbutton属性分配它时,它不会注意它们,它只是弹出当前视图并返回到根目录:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] 
                                  initWithTitle: @"Servers" 
                                  style:UIBarButtonItemStylePlain 
                                  target:self 
                                  action:@selector(home)];
self.navigationItem.backBarButtonItem = backButton;

一旦我通过leftBarButtonItem上的navigationItem设置它就会调用我的操作,但是按钮看起来像一个普通的圆形而不是向后箭头:

self.navigationItem.leftBarButtonItem = backButton;

如何在返回根视图之前调用自定义操作?有没有办法覆盖默认的后退操作,还是有一种方法在离开视图时总是被调用(viewDidUnload不这样做?)

28 个答案:

答案 0 :(得分:363)

尝试将其放入要检测印刷机的视图控制器中:

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
       // back button was pressed.  We know this is true because self is no longer
       // in the navigation stack.  
    }
    [super viewWillDisappear:animated];
}

答案 1 :(得分:173)

我已实施UIViewController-BackButtonHandler扩展。它不需要子类化任何东西,只需将它放入您的项目并覆盖navigationShouldPopOnBackButton类中的UIViewController方法:

-(BOOL) navigationShouldPopOnBackButton {
    if(needsShowConfirmation) {
        // Show confirmation alert
        // ...
        return NO; // Ignore 'Back' button this time
    }
    return YES; // Process 'Back' button click and Pop view controler
}

Download sample app

答案 2 :(得分:42)

与Amagrammer说,这是可能的。您必须继承navigationController。我解释了所有here(包括示例代码)。

答案 3 :(得分:13)

Swift版本:

https://stackoverflow.com/a/19132881/826435

在视图控制器中,您只需遵循协议并执行您需要的任何操作:

extension MyViewController: NavigationControllerBackButtonDelegate {
    func shouldPopOnBackButtonPress() -> Bool {
        performSomeActionOnThePressOfABackButton()
        return false
    }
}

然后创建一个类,比如NavigationController+BackButton,只需复制粘贴下面的代码:

protocol NavigationControllerBackButtonDelegate {
    func shouldPopOnBackButtonPress() -> Bool
}

extension UINavigationController {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        // Prevents from a synchronization issue of popping too many navigation items
        // and not enough view controllers or viceversa from unusual tapping
        if viewControllers.count < navigationBar.items!.count {
            return true
        }

        // Check if we have a view controller that wants to respond to being popped
        var shouldPop = true
        if let viewController = topViewController as? NavigationControllerBackButtonDelegate {
            shouldPop = viewController.shouldPopOnBackButtonPress()
        }

        if (shouldPop) {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            // Prevent the back button from staying in an disabled state
            for view in navigationBar.subviews {
                if view.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25, animations: {
                        view.alpha = 1.0
                    })
                }
            }

        }

        return false
    }
}

答案 4 :(得分:5)

不可能直接做。有几种选择:

  1. 创建您自己的自定义UIBarButtonItem,如果测试通过,则会自动点击并弹出
  2. 使用UITextField委托方法验证表单字段内容,例如-textFieldShouldReturn:,该方法在键盘上按下ReturnDone按钮后调用
  3. 第一个选项的缺点是无法通过自定义栏按钮访问后退按钮的左指箭头样式。因此,您必须使用图像或使用常规样式按钮。

    第二个选项很好,因为您在委托方法中返回了文本字段,因此您可以将验证逻辑定位到发送给委托回调方法的特定文本字段。

答案 5 :(得分:5)

出于某些线程原因,@ HansPinckaers提到的解决方案不适合我,但我找到了一种更容易触及后退按钮的方法,我想把它固定在这里以防万一这可以避免几个小时欺骗别人的。 诀窍很简单:只需将透明UIButton添加为UINavigationBar的子视图,并为他设置选择器,就像它是真正的按钮一样! 这是使用Monotouch和C#的一个例子,但是对objective-c的翻译不应该太难找到。

public class Test : UIViewController {
    public override void ViewDidLoad() {
        UIButton b = new UIButton(new RectangleF(0, 0, 60, 44)); //width must be adapted to label contained in button
        b.BackgroundColor = UIColor.Clear; //making the background invisible
        b.Title = string.Empty; // and no need to write anything
        b.TouchDown += delegate {
            Console.WriteLine("caught!");
            if (true) // check what you want here
                NavigationController.PopViewControllerAnimated(true); // and then we pop if we want
        };
        NavigationController.NavigationBar.AddSubview(button); // insert the button to the nav bar
    }
}

有趣的事实:出于测试目的并为我的假按钮找到好的尺寸,我将其背景颜色设置为蓝色......并且它显示后面的按钮!无论如何,它仍然可以捕获任何触摸目标原始按钮。

答案 6 :(得分:3)

找到了一个保留后退按钮样式的解决方案。 将以下方法添加到视图控制器。

-(void) overrideBack{

    UIButton *transparentButton = [[UIButton alloc] init];
    [transparentButton setFrame:CGRectMake(0,0, 50, 40)];
    [transparentButton setBackgroundColor:[UIColor clearColor]];
    [transparentButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:transparentButton];


}

现在根据需要提供以下方法中的功能:

-(void)backAction:(UIBarButtonItem *)sender {
    //Your functionality
}

所有这一切都是用透明按钮覆盖后退按钮;)

答案 7 :(得分:3)

此技术允许您更改“后退”按钮的文本,而不会影响任何视图控制器的标题或在动画期间看到后退按钮文本更改。

将此添加到调用视图控制器中的init方法:

UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];   
temporaryBarButtonItem.title = @"Back";
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
[temporaryBarButtonItem release];

答案 8 :(得分:3)

最简单的方法

您可以使用UINavigationController的委托方法。按下VC的后退按钮时会调用willShowViewController方法。按下btn后按下你想要的任何内容

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

答案 9 :(得分:2)

使用Swift:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.navigationController?.topViewController != self {
        print("back button tapped")
    }
}

答案 10 :(得分:2)

onegray的解决方案并不安全。根据Apple的官方文件https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html, 我们应该避免这样做。

&#34;如果在类别中声明的方法的名称与原始类中的方法相同,或者在同一个类(或甚至是超类)中的另一个类别中的方法相同,则行为未定义为在运行时使用哪种方法实现。如果您使用具有自己类的类别,则不太可能成为问题,但在使用类别向标准Cocoa或Cocoa Touch类添加方法时可能会出现问题。&#34;

答案 11 :(得分:2)

这是我的Swift解决方案。在UIViewController的子类中,重写navigationShouldPopOnBackButton方法。

extension UIViewController {
    func navigationShouldPopOnBackButton() -> Bool {
        return true
    }
}

extension UINavigationController {

    func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
        if let vc = self.topViewController {
            if vc.navigationShouldPopOnBackButton() {
                self.popViewControllerAnimated(true)
            } else {
                for it in navigationBar.subviews {
                    let view = it as! UIView
                    if view.alpha < 1.0 {
                        [UIView .animateWithDuration(0.25, animations: { () -> Void in
                            view.alpha = 1.0
                        })]
                    }
                }
                return false
            }
        }
        return true
    }

}

答案 12 :(得分:2)

通过继承UINavigationBar覆盖 ShouldPopItem 方法委托方法,有一种更简单的方法

答案 13 :(得分:2)

这是Swift 3版本的 @oneway 用于捕获导航栏后退按钮事件的答案。由于UIViewController无法用于navigationBar,因此您需要创建一个在调用shouldPop @objc public protocol BackButtonDelegate { @objc optional func navigationShouldPopOnBackButton() -> Bool } extension UINavigationController: UINavigationBarDelegate { public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool { if viewControllers.count < (navigationBar.items?.count)! { return true } var shouldPop = true let vc = self.topViewController if vc.responds(to: #selector(vc.navigationShouldPopOnBackButton)) { shouldPop = vc.navigationShouldPopOnBackButton() } if shouldPop { DispatchQueue.main.async { self.popViewController(animated: true) } } else { for subView in navigationBar.subviews { if(0 < subView.alpha && subView.alpha < 1) { UIView.animate(withDuration: 0.25, animations: { subView.alpha = 1 }) } } } return false } } 时触发的委托。

class BaseVC: UIViewController, BackButtonDelegate {
    func navigationShouldPopOnBackButton() -> Bool {
        if ... {
            return true
        } else {
            return false
        }        
    }
}

然后,在视图控制器中添加委托功能:

return false

我意识到我们经常想为用户添加一个警报控制器来决定他们是否想回去。如果是这样,您可以始终在navigationShouldPopOnBackButton()功能中func navigationShouldPopOnBackButton() -> Bool { let alert = UIAlertController(title: "Warning", message: "Do you want to quit?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { UIAlertAction in self.yes()})) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { UIAlertAction in self.no()})) present(alert, animated: true, completion: nil) return false } func yes() { print("yes") DispatchQueue.main.async { _ = self.navigationController?.popViewController(animated: true) } } func no() { print("no") } 并通过执行以下操作关闭视图控制器:

$('#table').append('<input type="text" class="integer">');// dynamically added input-box

$(".integer").on('keypress blur', function(e){
  return $.integer(e);
});

$(function(){
    $.integer = function(e){
        var arr = "1234567890";
        var code;
        if (window.event)
            code = e.keyCode;
        else
            code = e.which;
        var char = keychar = String.fromCharCode(code);
        if (arr.indexOf(char) == -1){
            return false;
        }
    };
});

答案 14 :(得分:2)

我不相信这是可能的,很容易。我认为解决这个问题的唯一方法就是让你自己的后退按钮箭头图像放在那里。起初这对我来说很令人沮丧,但我明白为什么,为了保持一致,它被排除在外。

您可以通过创建常规按钮并隐藏默认后退按钮来关闭(不带箭头):

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Servers" style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
self.navigationItem.hidesBackButton = YES;

答案 15 :(得分:1)

@William的答案是正确的,但是,如果用户开始向后滑动手势,则会调用viewWillDisappear方法,甚至self也不在导航堆栈中(也就是说,self.navigationController.viewControllers将不包含self),即使滑动未完成且视图控制器实际上未弹出。因此,解决方案是:

  1. 禁用viewDidAppear中的滑动到后退手势,并且只允许使用后退按钮,使用:

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
  2. 或者简单地使用viewDidDisappear,如下所示:

    - (void)viewDidDisappear:(BOOL)animated
    {
        [super viewDidDisappear:animated];
        if (![self.navigationController.viewControllers containsObject:self])
        {
            // back button was pressed or the the swipe-to-go-back gesture was
            // completed. We know this is true because self is no longer
            // in the navigation stack.
        }
    }
    

答案 16 :(得分:1)

夫特

override func viewWillDisappear(animated: Bool) {
    let viewControllers = self.navigationController?.viewControllers!
    if indexOfArray(viewControllers!, searchObject: self) == nil {
        // do something
    }
    super.viewWillDisappear(animated)
}

func indexOfArray(array:[AnyObject], searchObject: AnyObject)-> Int? {
    for (index, value) in enumerate(array) {
        if value as UIViewController == searchObject as UIViewController {
            return index
        }
    }
    return nil
}

答案 17 :(得分:1)

Swift 4 iOS 11.3版本:

这是基于来自https://stackoverflow.com/a/34343418/4316579

的kgaidis的回答

我不确定扩展何时停止工作,但在撰写本文时(Swift 4),除非您按照以下说明声明UINavigationBarDelegate符合性,否则将不再执行扩展。

希望这可以帮助那些想知道为什么他们的扩展不再有效的人。

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {

    }
}

答案 18 :(得分:1)

使用isMovingFromParentViewController

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(true)

    if self.isMovingFromParentViewController {
        // current viewController is removed from parent
        // do some work
    }
}

答案 19 :(得分:1)

通过使用当前离开'nil'的目标和动作变量,您应该能够连接保存对话框,以便在按钮被“选中”时调用它们。请注意,这可能会在奇怪的时刻触发。

我主要与Amagrammer达成一致,但我认为用按钮定制按钮并不难。我只需要重命名后退按钮,拍摄一个屏幕截图,然后按照所需的按钮尺寸,将其作为按钮顶部的图像。

答案 20 :(得分:1)

至少在Xcode 5中,有一个简单而且非常好(不完美)的解决方案。在IB中,将“按钮项”拖出“实用工具”窗格,然后将其放在导航栏左侧的“后退”按钮所在的位置。将标签设置为&#34; Back。&#34;你将有一个功能按钮,你可以绑定到你的IBAction并关闭你的viewController。我正在做一些工作,然后触发一个放松的segue,它运作得很好。

理想的是,这个按钮没有得到&lt;箭头并没有结转以前的VC冠军,但我认为这可以管理。为了我的目的,我将新的后退按钮设置为&#34;完成&#34;按钮,所以它的目的很明确。

您最终还是在IB导航器中有两个Back按钮,但为了清晰起见,它很容易标记。

enter image description here

答案 21 :(得分:1)

对于需要这样的用户输入的表单,我建议将其调用为“模态”而不是导航堆栈的一部分。这样他们就必须在表单上处理业务,然后你可以使用自定义按钮对其进行验证并解除它。您甚至可以设计一个与应用程序其余部分看起来相同的导航栏,但为您提供更多控制权。

答案 22 :(得分:1)

您可以尝试访问NavigationBars右键按钮项目并设置其选择器属性...继承人引用UIBarButtonItem reference,如果这个最干净的工作将是def工作的另一件事是,设置导航栏的右键项目到您创建并设置其选择器的自定义UIBarButtonItem ...希望这有帮助

答案 23 :(得分:0)

找到新方法:

目标C

- (void)didMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        NSLog(@"Back Pressed");
    }
}

夫特

override func didMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        println("Back Pressed")
    }
}

答案 24 :(得分:0)

到目前为止我找到的解决方案并不是很好,但它对我有用。考虑这个answer,我还会检查是否以编程方式弹出:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if ((self.isMovingFromParentViewController || self.isBeingDismissed)
      && !self.isPoppingProgrammatically) {
    // Do your stuff here
  }
}

您必须将该属性添加到控制器并在以编程方式弹出之前将其设置为YES:

self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];

答案 25 :(得分:0)

要拦截“后退”按钮,只需用透明的UIControl覆盖它并拦截触摸。

@interface MyViewController : UIViewController
{
    UIControl   *backCover;
    BOOL        inhibitBackButtonBOOL;
}
@end

@implementation MyViewController
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Cover the back button (cannot do this in viewWillAppear -- too soon)
    if ( backCover == nil ) {
        backCover = [[UIControl alloc] initWithFrame:CGRectMake( 0, 0, 80, 44)];
#if TARGET_IPHONE_SIMULATOR
        // show the cover for testing
        backCover.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.15];
#endif
        [backCover addTarget:self action:@selector(backCoverAction) forControlEvents:UIControlEventTouchDown];
        UINavigationBar *navBar = self.navigationController.navigationBar;
        [navBar addSubview:backCover];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [backCover removeFromSuperview];
    backCover = nil;
}

- (void)backCoverAction
{
    if ( inhibitBackButtonBOOL ) {
        NSLog(@"Back button aborted");
        // notify the user why...
    } else {
        [self.navigationController popViewControllerAnimated:YES]; // "Back"
    }
}
@end

答案 26 :(得分:0)

@ onegray的答案的快速版本

protocol RequestsNavigationPopVerification {
    var confirmationTitle: String { get }
    var confirmationMessage: String { get }
}

extension RequestsNavigationPopVerification where Self: UIViewController {
    var confirmationTitle: String {
        return "Go back?"
    }

    var confirmationMessage: String {
        return "Are you sure?"
    }
}

final class NavigationController: UINavigationController {

    func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {

        guard let requestsPopConfirm = topViewController as? RequestsNavigationPopVerification else {
            popViewControllerAnimated(true)
            return true
        }

        let alertController = UIAlertController(title: requestsPopConfirm.confirmationTitle, message: requestsPopConfirm.confirmationMessage, preferredStyle: .Alert)

        alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
            dispatch_async(dispatch_get_main_queue(), {
                let dimmed = navigationBar.subviews.flatMap { $0.alpha < 1 ? $0 : nil }
                UIView.animateWithDuration(0.25) {
                    dimmed.forEach { $0.alpha = 1 }
                }
            })
            return
        })

        alertController.addAction(UIAlertAction(title: "Go back", style: .Default) { _ in
            dispatch_async(dispatch_get_main_queue(), {
                self.popViewControllerAnimated(true)
            })
        })

        presentViewController(alertController, animated: true, completion: nil)

        return false
    }
}

现在在任何控制器中,只需符合RequestsNavigationPopVerification,默认情况下会采用此行为。

答案 27 :(得分:0)

Swift5 中的 UIAlert 以以前的回复为基础,以异步方式


protocol NavigationControllerBackButtonDelegate {
    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ())
}

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {

        if viewControllers.count < navigationBar.items!.count {
            return true
        }

        // Check if we have a view controller that wants to respond to being popped

        if let viewController = topViewController as? NavigationControllerBackButtonDelegate {

            viewController.shouldPopOnBackButtonPress { shouldPop in
                if (shouldPop) {
                    /// on confirm => pop
                    DispatchQueue.main.async {
                        self.popViewController(animated: true)
                    }
                } else {
                    /// on cancel => do nothing
                }
            }
            /// return false => so navigator will cancel the popBack
            /// until user confirm or cancel
            return false
        }else{
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        }
        return true
    }
}


在您的控制器上


extension MyController: NavigationControllerBackButtonDelegate {

    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ()) {

        let msg = "message"

        /// show UIAlert
        alertAttention(msg: msg, actions: [

            .init(title: "Continuer", style: .destructive, handler: { _ in
                completion(true)
            }),
            .init(title: "Annuler", style: .cancel, handler: { _ in
                completion(false)
            })
            ])

    }

}