iOS 模態視圖 demo


 

 

 

ios開發中,在當前視圖上再彈出一個視圖(模態視圖),實現一個簡單的多視圖應用,下面小弟給大家寫個demo

一 。新建一個工程,選單視圖應用模版

建好后如下圖

下面稍稍修改一下ViewController.m

添加一個button用於在當前視圖上彈出一個模態視圖

 

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor]; //添加彈出模態視圖按鈕
    UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(120, 220, 80, 40)]; [button setTitle:@"模態視圖" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } -(void)buttonPressed { }

接下來新建一個試圖控制器,用來展示點擊按鈕后要彈出的視圖

在新建的類里添加下面代- (void)viewDidLoad

{ [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor purpleColor]; UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(130, 50, 60, 20)]; [button setTitle:@"返回" forState:UIControlStateNormal]; [button addTarget:self action:@selector(back ) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } -(void)back { //[self dismissModalViewControllerAnimated:YES];6.0 不能用

//下面這行代碼作用就是將彈出的模態視圖移除,第一個yes表示移除的時候有動畫效果,第二參數是設置一個回調,當模態視圖移除消失后,會回到這里,可以在這里隨便寫句話打個斷點,試一下就知道確實會回調到這個方法

    [selfdismissViewControllerAnimated:YEScompletion:^{

 
         

        NSLog(@"back");//這里打個斷點,點擊按鈕模態視圖移除后會回到這里

 //ios 5.0以上可以用該方法
 
         

    }];

 
         

}

下面回到ViewController.m中為視圖按鈕添加彈出模態視圖方法

-(void)buttonPressed
{
    ModalViewController * modalView = [[ModalViewController alloc]init];
    modalView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
   // [self presentModalViewController:modalView animated:YES];  ios 6 棄用了該方法
    [self presentViewController:modalView animated:YES completion:nil];
    [modalView release];
}

最后運行效果

點擊模態視圖按鈕后,程序如下圖

程序默認的動畫效果是從下往上彈出,可以改modalTransitionStyle換

成其他效果

    modalView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {

    UIModalTransitionStyleCoverVertical = 0,//默認垂直向上

    UIModalTransitionStyleFlipHorizontal, 翻轉效果

    UIModalTransitionStyleCrossDissolve,淡入淡出

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2

    UIModalTransitionStylePartialCurl,翻頁效果

#endif

};

 

需要注意的地方 :1.在彈出的模態視圖上點擊返回按鈕后,該視圖對象徹底被釋放了,記得要將添加到該視圖上的一些對象都寫在

dealloc方法中

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM