![](/img/trans.png)
[英]How can I go back to the first viewController from the third viewController
[英]Swift Navigate from third ViewController to the first ViewController
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(identifier:
"PersonViewController") as? PersonViewController
vc?.names = persons[indexPath.row].emer!
vc?.lastnames = persons[indexPath.row].mbiemer!
vc?.delegate = self
PersonViewController.indexes = indexPath.row
self.navigationController?.pushViewController(vc!, animated: true)
}`
我有這樣的情況:
第一個 ViewController 是一個 collectionView,第二個是一個視圖控制器,當我點擊一個按鈕時它可以添加新的 Person 並且完美地工作。 我已經將委托和核心數據用於本地內存。
此外,第二個 ViewController 有另一個按鈕來編輯人員。 當我按下按鈕時,會出現一個帶有擴展名UIAdaptivePresentationControllerDelegate
的新UIAdaptivePresentationControllerDelegate
。 此視圖控制器由 2 個按鈕和 2 個文本字段組成。 因此,當我想按保存按鈕時,我想轉到第一個視圖控制器(集合視圖列表),何時按取消返回到第二個視圖控制器。
視圖控制器是使用 pushViewController 方法創建的。
請任何人幫助我應該使用什么?
然后在 PersonViewController 中,我將其稱為內部按鈕編輯。
@objc func editCell(){
let vc = storyboard?.instantiateViewController(identifier:
"ModalPresentationViewController") as?
ModalPresentationViewController
navigationController?.pushViewController(vc!, animated: true)
}
現在 las ViewController 中的代碼是 ModalViewController
@objc func savePerson(){
if editNameTextfield.text == "" || editlastNameTextfield.text == ""{
self.errorLbl.alpha = 1
}
else{
let vc = ViewController()
guard let textName = editNameTextfield.text else{
return
}
guard let textLastName = editlastNameTextfield.text else{
return
}
let index = PersonViewController.indexes
DispatchQueue.main.async {[self] in
if editDelegate != nil{
self.editDelegate!.editPerson(editedName: textName, editedLastname: textLastName, index: index)
}
}
// What should I call here??
}
}
您可以使用以下內容:
func popTo(_ type: AnyClass) {
guard let controllers = navigationController?.viewControllers else {return}
for controller in controllers {
if controller.classForCoder == type {
navigationController?.popToViewController(controller, animated: true)
break
}
}
}
並根據條件調用函數:
popTo(A.classForCoder())
編輯:上述解決方案僅當 ViewControllers B 和 C 通過導航控制器呈現並且位於同一導航堆棧中時才有效。
由於您以模態方式呈現 ViewController C,因此以下答案應該有效:
對呈現 C 的 ViewController B 進行這些更改:
class B: UIViewController, PresenterDelegate {
// some functions
func popToPrevious() {
navigationController.popViewController(animated: false)
}
@objc func editCell(){
let vc = storyboard?.instantiateViewController(identifier:
"ModalPresentationViewController") as?
ModalPresentationViewController
vc.presenterDelegate = self
present(vc, animated: true, completion: nil)
}
}
在你的 ViewController C 中:
class C {
var presenterDelegate: PresenterDelegate? = nil
//
@objc func savePerson(){
//
//
dismiss(animated: true, completion: {
self.presenterDelegate?.popToPrevious()
})
}
}
還將 PresenterDelegate 協議添加到新文件或 ViewControllers B 或 C 之下
protocol PresenterDelegate {
func popToPrevious()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.