首页 文章

检测是否按下导航栏中的默认后退按钮

提问于
浏览
0

我知道有这样的答案,如制作自定义按钮然后进行操作,但我不想用箭头更改默认后退按钮,我也尝试这样:

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}

这里的问题是,即使按下我在该视图控制器中也有的保存按钮,也会调用此函数 . 我只需要在按下后退按钮时检测

2 回答

  • 0

    在viewWillDisappear方法中,添加 isMovingFromParentViewController 属性:

    if self.isMovingFromParentViewController {
        //do stuff, the back button was pressed
    }
    

    编辑:正如已经指出的,如果您只是在按下保存按钮时解除视图控制器,则需要 Bool 值来检查是否按下了保存按钮或默认后退按钮 .

    在类的顶部,定义一个布尔值:

    var saveButtonPressed = false
    

    我假设您有一个链接到保存按钮的 @IBAction 方法 . 如果你不这样做,那么我建议你添加这个连接 .

    在该方法中,将 saveButtonPressed 设置为等于true .

    然后,在viewWillDisappear方法中,将其添加到if条件:

    if (self.isMovingFromParentViewController && !saveButtonPressed) {
        //do stuff, the back button was pressed
    }
    
  • 0

    如果Xcoder提供的答案不符合您的要求,请检查此答案

    https://stackoverflow.com/a/37230710/1152683

    它包括创建自定义按钮,但带有箭头 . 检查整个代码的答案

    用法非常简单

    weak var weakSelf = self
    
    // Assign back button with back arrow and text (exactly like default back button)
    navigationItem.leftBarButtonItems = CustomBackButton.createWithText("YourBackButtonTitle", color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))
    
    // Assign back button with back arrow and image
    navigationItem.leftBarButtonItems = CustomBackButton.createWithImage(UIImage(named: "yourImageName")!, color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))
    
    func tappedBackButton() {
    
        // Do your thing
    
    }
    

    编辑:

    保持原始按钮

    知道了,对你来说这不起作用

    override func viewWillDisappear(_ animated : Bool) {
        super.viewWillDisappear(animated)
        if self.isMovingFromParentViewController {
         print("something")
        }
    }
    

    我只能假设当点击保存按钮时你导航到前一个屏幕,你必须在该函数内添加一个标志,然后像这样添加一个条件到那个函数

    override func viewWillDisappear(_ animated : Bool) {
        super.viewWillDisappear(animated)
        if self.isMovingFromParentViewController && !save {
           // back pressed
        }
    }
    

    作为保存变量的Bool在点击保存按钮时变为真

相关问题