1. 程式人生 > 其它 >IOS開發之——Modal原理和常規使用(65)

IOS開發之——Modal原理和常規使用(65)

技術標籤:IOSios

一 概述

  • 除了push之外,還有另外一種控制器的切換方式,那就是Modal
  • 任何控制器都能通過Modal的形式展示出來
  • Modal的預設效果:新控制器從螢幕的最底部往上鑽,知道蓋住之前的控制器為止

二 Modal的開啟及關閉

2.1 Modal形式展示控制器

-(void)presentViewCOntroller:(UIViewCOntroller *)viewCOntrollerToPresent animated:(BOOL)flag completion:(void^)completion

2.2 關閉Modal出來的控制器

self dismissViewControllerAnimated:<#(BOOL)#> completion:<#^(void)completion#>

三 簡單示例

3.1 介面關係

  • FirstVIewController(第一個頁面),有一個按鈕,點選跳轉到JumpViewController
  • JumpViewController(跳轉到的頁面),有一個返回按鈕,點選返回到FirstViewController

3.2 程式碼

FirstVIewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeContactAdd];
    btn.center=self.view.center;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)btnClick{
    //建立控制器物件
    JumpViewController *jump=[[JumpViewController alloc]init];
    //Modal出一個控制器
    //[self presentModalViewController:jump animated:YES];
     
    [self presentViewController:jump animated:YES completion:nil];
}

JumpViewController

- (IBAction)cancel:(UIButton *)sender {
    //關閉
    [self dismissViewControllerAnimated:YES completion:nil];
}

3.3 效果圖

四 通過導航條方式關閉Modal

4.1 介面修改說明

  • 去掉JumpViewController中去掉按鈕
  • 通過導航條做按鈕做返回操作

4.2 程式碼

FirstVIewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeContactAdd];
    btn.center=self.view.center;
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)btnClick{
    //建立控制器物件
    JumpViewController *jump=[[JumpViewController alloc]init];
    //Modal出一個控制器
    //[self presentModalViewController:jump animated:YES];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:jump];
     
    [self presentViewController:nav animated:YES completion:nil];
}

JumpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];  
}
- (IBAction)cancel{
    //關閉
    [self dismissViewControllerAnimated:YES completion:nil];
}

4.3 效果圖