导航到同一屏幕,但从两个不同的ViewController

时间:2019-01-17 07:14:35

标签: ios swift uinavigationcontroller

所以我有3个VC

ViewController1,ViewController2,ViewController3

现在,我在ViewController2ViewController3中都有一个按钮,点击该按钮将导航到ViewController1 从vc2导航时和从vc3导航时,UI都有轻微的变化。

所以我想知道处理这个问题的最佳实践。我怎么知道我从哪个vc到达VC1 ??

3 个答案:

答案 0 :(得分:2)

您可以使用标志或枚举。我建议对于enum bcz,将来有时您可能会从多个控制器推送到VC​​1。使用枚举始终很方便。

  
      
  1. 带有标志
  2.   
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
    }
    
  
      
  1. 使用枚举
  2.   
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)
  • 更多信息

enter image description here

答案 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}}
相关问题