当用户点击按钮时,我会将用户发送到一个页面。这个页面是一个UITableViewController。
现在,如果用户点击单元格,我希望将其推回到上一个页面。
我考虑过像self.performSegue("back")....
这样的方法,但这似乎是个坏主意。
正确的做法是什么?
当用户点击按钮时,我会将用户发送到一个页面。这个页面是一个UITableViewController。
现在,如果用户点击单元格,我希望将其推回到上一个页面。
我考虑过像self.performSegue("back")....
这样的方法,但这似乎是个坏主意。
正确的做法是什么?
Swift 3:
如果您想返回到上一个视图控制器
_ = navigationController?.popViewController(animated: true)
如果您想返回到根视图控制器
_ = navigationController?.popToRootViewController(animated: true)
如果您没有使用导航控制器,请使用以下代码。
self.dismiss(animated: true, completion: nil)
动画值可以根据您的要求进行设置。
.popViewController(animated: true)
。 - Sasho_ = self.navigationController?.popToRootViewController(animated: true)
。翻译说明:
这是一行 Swift 代码,它的作用是将当前视图控制器导航到其根视图控制器。该代码中的问号表示 navigationController
属性可能为空,popToRootViewController
是导航控制器的一个方法,通过传递 animated: true
参数来启用动画效果。在这里,下划线 _
表示我们不需要使用这个方法返回的任何值。 - Andrew K_ =
是惯例。 - Andrew KSwift 3,Swift 4
if movetoroot {
navigationController?.popToRootViewController(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
navigationController是可选的,因为可能不存在。
[weak self]
和self?.navigationController?.
。 - Vyacheslav{
if let vc = segue.destination as?```
但当我使用它时,我不能使用那个。
- Saeed RahmatolahiSwift 5及以上版本
案例1:与导航控制器一起使用
返回到上一个视图控制器self.dismiss(animated: true, completion: nil)
Swift 3
我可能回答晚了,但对于Swift 3,您可以按照以下方法操作:
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))
// Do any additional setup if required.
}
func backAction(){
//print("Back Button Clicked")
dismiss(animated: true, completion: nil)
}
dismiss:
方法,它不仅会关闭当前的视图控制器,还会关闭根视图控制器,这并不是被要求的结果。 - Ernesto Fernandezdismiss(animated: true, completion: nil)
无法工作! - user924Swift 4
有两种方法返回到前一个ViewController:
self.navigationController?.pushViewController(yourViewController, animated: true)
,在这种情况下,你需要使用self.navigationController?.popViewController(animated: true)
self.present(yourViewController, animated: true, completion: nil)
,在这种情况下,你需要使用self.dismiss(animated: true, completion: nil)
在第一种情况下,请确保在你的storyboard中将ViewController嵌入到navigationController中
如果您在一个UIViewController
中呈现了另一个UIViewController
,也就是说...
// Main View Controller
self.present(otherViewController, animated: true)
只需调用 dismiss
函数:
// Other View Controller
self.dismiss(animated: true)
对于Swift 3,您只需要编写以下代码行:
_ = navigationController?.popViewController(animated: true)
这个对我有效(Swift UI)
struct DetailView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is the detail view")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Back")
}
}
}
}
navigationController?.popViewController(animated: true)
使用以下代码返回到根视图:
navigationController?.popToRootViewController(animated: true)