[ios开发中自定义按钮并跳转页面]iOS开发中自定义按钮并跳转到另外一个视图实例

更新时间:2019-10-08    来源:ios    手机版     字体:

【www.bbyears.com--ios】

刚学iOS不久,虽然视图切换能直接用stroryboard创建,拖根线就完事了!但不知道为嘛,还是感觉iOS开发中代码控制视图灵活方便。

不多说了,开始今天的笔记:

新建工程,不多说啦!我喜欢用Empty Application,创建完成后,新建两个UIViewController类,假设A和B吧!!哈哈

这儿将appDelegate中的代码就省了!!哈哈。相信能看到这儿的人,也懂得如何设置root视图了

我们要实现的是,从A点击一个按钮,弹出来B窗口,然后点击B窗口的一个按钮,返回到A窗口。

直接开始代码:
A:

- (void)viewDidLoad
{
    [super viewDidLoad];
//设置视图背景颜色
    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(modelViewGO) forControlEvents:UIControlEventTouchUpInside];
//添加进视图
    [self.view addSubview:button];
}

-(void) modelViewGO
{
    BViewController * modalView = [[BViewController alloc]init];
    modalView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
   
    [self presentViewController:modalView animated:YES completion:nil];
//    [modalView release];
}

然后在B视图中,添加返回按钮及相关代码:
B:

- (void)viewDidLoad
{
//和A视图差不多的东西,不解释啦!!
    [super viewDidLoad];
    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
{
//下面这行代码作用就是将弹出的模态视图移除,第一个yes表示移除的时候有动画效果,第二参数是设置一个回调,当模态视图移除消失后,会回到这里,可以在这里随便写句话打个断点,试一下就知道确实会回调到这个方法
//    [self dismissViewControllerAnimated:YES completion:nil]; 或带有回调的如下方法
    [self dismissViewControllerAnimated:YES completion:^{

        NSLog(@"back");//这里打个断点,点击按钮模态视图移除后会回到这里
 //ios 5.0以上可以用该方法
    }];
}

程序默认的动画效果是从下往上弹出,可以改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方法中

本文来源:http://www.bbyears.com/shoujikaifa/71918.html

热门标签

更多>>

本类排行