Don_Mag icon

Modify Navigation Controller stack

Don_Mag | PRO | 01/05/23 11:53:19 AM UTC (Edited) | 0 ⭐ | 7976 👁️ | Never ⏰ | []
Swift |

1.85 KB

|

None

|

0 👍

/

0 👎

// embed FirstVC as the Root View Controller of a Navigation Controller
 
class FirstVC: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .yellow
        
        let button = UIButton(type: .system, primaryAction: UIAction(title: "Push to Second VC", handler: { _ in
            let vc = SecondVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }))
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
        
    }
    
}
 
class SecondVC: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .green
        
        let button = UIButton(type: .system, primaryAction: UIAction(title: "Push to Third VC", handler: { _ in
            let vc = ThirdVC()
            self.navigationController?.pushViewController(vc, animated: true)
        }))
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
        
    }
    
}
 
class ThirdVC: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .cyan
        
        let v = UILabel()
        v.text = "This is Third VC"
        view.addSubview(v)
        v.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            v.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            v.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
        
        
        if let navC = self.navigationController {
            var a = navC.viewControllers
            a.remove(at: 1)
            navC.setViewControllers(a, animated: false)
        }
    }
    
}
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎