Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active January 28, 2021 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/6dc2dd1051126b8b24c959d82ffca151 to your computer and use it in GitHub Desktop.
Save woodycatliu/6dc2dd1051126b8b24c959d82ffca151 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// Created by Woody on 2021/1/28.
/*
a simple example for removing the superimposed ViewController behind
*/
import UIKit
class ViewController: UIViewController {
lazy var button: UIButton = {
let b = UIButton()
b.setTitle("GO", for: .normal)
b.addTarget(self, action: #selector(press), for: .touchUpInside)
b.setTitleColor(.red, for: .normal)
b.backgroundColor = .white
return b
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.widthAnchor.constraint(equalToConstant: 50).isActive = true
button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
private func getViewController()-> UIViewController {
let vc = ViewController()
vc.view.backgroundColor = .blue
return vc
}
/// point this order, The first step is push New ViewController
@objc func press() {
let vc = getViewController()
navigationController?.pushViewController(vc, animated: true)
removeSurplusViewController()
}
private func removeSurplusViewController() {
guard let viewControllers = self.navigationController?.viewControllers, viewControllers.count >= 3 else { return }
for vc in viewControllers where vc.view.backgroundColor == UIColor.blue {
// filter the specific ViewController and remove unnecessary others
guard let count = navigationController?.viewControllers.filter({ $0.view.backgroundColor == UIColor.blue }).count
, count > 1 else { return }
// find the index from navigationController?.viewControllers
if let index = self.navigationController?.viewControllers.firstIndex(of: vc){
self.navigationController?.viewControllers.remove(at: index)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment