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