八亿电脑网
游戏盒子
当前位置: 首页 > 手机之家 > 苹果学院 >

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

时间:2015-03-19 10:34来源:网络 作者:win8e 点击:
游戏盒子

本文我们来分享在ios开发中如何通过自定义按钮并跳转到另外一个视图的学习实例,这种场景在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方法中

发表评论