1. 程式人生 > >IOS初學-檢視控制器的跳轉方式 入棧和出棧

IOS初學-檢視控制器的跳轉方式 入棧和出棧

新建專案。建立ThreeSubViewController檢視控制器

在ThreeSubViewController中定義一個全域性變數記錄編號

//記錄 檢視控制器編號的全域性變數
var pageNum=0;

控制器中每建立一次。增加一次編號。定義四個button新增到根檢視總   實現四個不同的功能

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", for: UIControlState());
        push.backgroundColor=UIColor.orange;
        push.addTarget(self, action: #selector(ThreeSubViewController.push), for: UIControlEvents.touchUpInside);
        self.view.addSubview(push);
        
        let pop = UIButton(frame: CGRect(x: 40, y: 170, width: 240, height: 40 ))
        pop.setTitle("pot", for: UIControlState());
        pop.backgroundColor=UIColor.orange;
        pop.addTarget(self, action: #selector(ThreeSubViewController.pop), for: UIControlEvents.touchUpInside);
        self.view.addSubview(pop);
        
        let index = UIButton(frame: CGRect(x: 40, y: 220, width: 240, height: 40));
        index.setTitle("index", for: UIControlState());
        index.backgroundColor=UIColor.orange;
        index.addTarget(self, action: #selector(ThreeSubViewController.toIndex), for: UIControlEvents.touchUpInside);
        self.view.addSubview(index);
        
        let rootPage = UIButton(frame: CGRect(x: 40, y: 270, width: 240, height: 40));
        rootPage.setTitle("rootPage", for: UIControlState());
        rootPage.backgroundColor=UIColor.orange;
        rootPage.addTarget(self, action: #selector(ThreeSubViewController.rootPage), for: UIControlEvents.touchUpInside);
        self.view.addSubview(rootPage);
    }

 

實現四個button的點選事件

 @objc func push(){
		//進入下一頁
        self.navigationController?.pushViewController(ThreeSubViewController(), animated: true);
    }
    @objc func pop(){
		//返回上一頁
        self.navigationController?.popViewController(animated: true);
    }
    @objc func toIndex(){
		//進入制定位置
        self.navigationController?.popToViewController((self.navigationController?.viewControllers[2])!, animated: true);
    }
    @objc func rootPage(){
		//返回根檢視頁面
        self.navigationController?.popToRootViewController(animated: true);
    }

在程式中設定入口

let navigationController=UINavigationController(rootViewController: ThreeSubViewController());
self.window?.rootViewController=navigationController;