[英]Navigate to same screen but from two different viewcontroller
所以我有3个VC
ViewController1,ViewController2,ViewController3
现在,我在ViewController2
和ViewController3
都有一个按钮,通过点击它们导航到ViewController1
,从vc2导航和从vc3导航时,UI会有微小的变化。
所以我想知道处理这个问题的最佳实践。 我怎么知道从哪个vc到达VC1
??
您可以使用标志或枚举。 我建议对于enum bcz,将来有时您可能会从多个控制器推送到VC1。 使用枚举始终很方便。
- 带标志
class ViewController1: UIViewController {
// default value is false bcz if you forgot to assign this value then atleast your app won't crash.
var isFromVC2 : Bool = false
:
:
}
使用->在您的VC1文件中
if isFromVC2 { // Do code for VC2 } else { // Do code for VC3 }
- 与枚举
enum ComingFrom {
case VC3
case VC2
}
class ViewController: UIViewController {
// default value VC2
var whichController : ComingFrom = .VC2
:
:
}
采用
switch whichController { case .VC2: // for vc2 Code case .VC3: // for VC3 Code default: // If you forget to assign `whichController` or there will be new condition in future }
编辑:如何分配whichController
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
vc.whichController = .VC2
self.navigationController?.pushViewController(vc, animated: true)
在VC1中,创建一个变量作为vcNames。
class VC1: UIViewController {
var vcNames = ""
override func viewDidLoad() {
super.viewDidLoad()
//Check your vc's with vcNames.
}
}
现在,当从VC2或VC3推送到vc1时,只需将当前的vc名称传递给创建的变量即可。
let tempVC1 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "VC1") as? VC1
tempVC1?.vcNames = "vc2" //Assign your vc name here
self.navigationController?.pushViewController(tempVC1!, animated: true)
添加唯一的Bool
变量,以便您可以了解该控制器的使用位置。 在viewWillAppear
中将flag false
,因为每次对其进行更新都是可以实现的最简单的方法。
class ViewController1: UIViewController {
var isFromVC2 = false
var isFromVC3 = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
isFromVC2 = false
isFromVC3 = false
}
}
class ViewController2: UIViewController {
//You can call this function from where you want otherwise you can make it global.
func navigateToVC1() {
let viewController1 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
viewController1.isFromVC2 = true
self.navigationController?.pushViewController(viewController1, animated: true)
}
}
class ViewController3: UIViewController {
func navigateToVC1() {
let viewController1 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController1") as! ViewController1
viewController1.isFromVC3 = true
self.navigationController?.pushViewController(viewController1, animated: true)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.