所以我有3个VC
ViewController1,ViewController2,ViewController3
现在,我在ViewController2
和ViewController3
中都有一个按钮,点击该按钮将导航到ViewController1
从vc2导航时和从vc3导航时,UI都有轻微的变化。
所以我想知道处理这个问题的最佳实践。我怎么知道我从哪个vc到达VC1
??
答案 0 :(得分:2)
您可以使用标志或枚举。我建议对于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)
答案 1 :(得分:1)
在您的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)
答案 2 :(得分:1)
添加唯一的Bool
变量,以便您了解该控制器的位置。
在flag false
中将viewWillAppear
设为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)
}
}
,因为每次更新都应以最简单的方式实现。
{{1}}