版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21153627/article/details/83991353
新建项目。创建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;