首先要在appDelegate里添加导航视图控制器navigationColler
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let navigationController = UINavigationController(rootViewController: FirstViewController())
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
然后在初始视图控制器里添加代码(我这里是FirstViewContriller)
import UIKit
var pageNum = 0
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
pageNum = pageNum + 1
self.title = "Page\(pageNum)"
self.view.backgroundColor = UIColor.purple
let push = UIButton(frame: CGRect(x: 40, y: 120, width: 240, height: 40))
push.setTitle("Push page", for: UIControlState())
push.backgroundColor = UIColor.orange
push.addTarget(self, action: #selector(pushPage), for: UIControlEvents.touchUpInside)
self.view.addSubview(push)
let pop = UIButton(frame: CGRect(x: 40, y: 180, width: 240, height: 40))
pop.setTitle("Pop Page", for: UIControlState())
pop.backgroundColor = UIColor.orange
pop.addTarget(self, action: #selector(popPage), for: UIControlEvents.touchUpInside)
self.view.addSubview(pop)
let index = UIButton(frame: CGRect(x: 40, y: 280, width: 240, height: 40))
index.setTitle("Goto Index Page", for: UIControlState())
index.backgroundColor = UIColor.orange
index.addTarget(self, action: #selector(gotoIndexPage), for: UIControlEvents.touchUpInside)
self.view.addSubview(index)
let root = UIButton(frame: CGRect(x: 40, y: 340, width: 240, height: 40))
root.setTitle("Goto root Page", for: UIControlState())
root.backgroundColor = UIColor.orange
root.addTarget(self, action: #selector(gotoRootPage), for: UIControlEvents.touchUpInside)
self.view.addSubview(root)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func pushPage(){
let viewController = FirstViewController()
self.navigationController?.pushViewController(viewController, animated: true)
}
@objc func popPage(){
self.navigationController?.popViewController(animated: true)
}
@objc func gotoIndexPage(){
let viewController = self.navigationController?.viewControllers[1]
self.navigationController?.popToViewController(viewController!, animated: true)
}
@objc func gotoRootPage(){
self.navigationController?.popToRootViewController(animated: true)
}
}
运行一下查看效果吧!