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

gfttwv5a  于 12个月前  发布在  iOS
关注(0)|答案(2)|浏览(93)

我知道有这样的答案,如使自定义按钮,然后使行动,但我不想改变默认的返回按钮与箭头,我也这样尝试:

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

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

c9x0cxw0

c9x0cxw01#

在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
}
6rqinv9w

6rqinv9w2#

如果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在点击保存按钮时变为true

相关问题