簡體   English   中英

檢測是否按下導航欄中的默認后退按鈕

[英]Detect if default back button in navigation bar is pressed

我知道有這樣的答案,例如制作自定義按鈕,然后執行操作,但是我不想用箭頭更改默認的后退按鈕,我也嘗試這樣:

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

這里的問題是,即使我按下該視圖控制器中同樣具有的保存按鈕,也會調用此函數。 我只需要在按下后退按鈕時進行檢測

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

如果Xcoder提供的答案不符合您的要求,請檢查此一項

https://stackoverflow.com/a/372​​30710/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
    }
}

是保存變量,當點擊保存按鈕時,布爾值變為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM