view制作及切换
目的
学习view制作及切换的几种方式
?
环境
Mac OS X 10.7.2
Xcode4.2
?
详解
在storyboard中创建另一个ViewController并使用Segue切换
在storyboard中再增加一个ViewController。在两个ViewController中各增加一个按钮。右击按钮,在弹出菜单中拖放“Modal”圈圈到另一个ViewController上放手即可。
?
在xib文件中创建另一个ViewController并使用代码手动切换
在工程中添加文件,选择创建“UIViewController subclass”,在向导中勾选“With XIB for user interface”,取名为“SecondViewController”,完成后得到3个文件:"SecondViewController.h"、"SecondViewController.m“、"SecondViewController.xib”。
在xib中添加一个按钮,并为其添加事件处理函数,在函数中增加如下代码以用于退出当前的view回到首页:
?
- (IBAction)exitCurrentView:(id)sender {?
??? [self.view removeFromSuperview];?
}?
在首页的ViewController.h中添加此xib对应的变量,如下所示:
?
@interface ViewController : UIViewController?
{?
??? SecondViewController* secondViewController;?
}?
?
背后的切换按钮事件函数代码为:
?
- (IBAction)switchToSecondView:(id)sender {?
??? secondViewController=[[SecondViewController new]?
????????????????????????? initWithNibName:@"SecondViewController"?
????????????????????????? bundle:nil];?
??? [self.view addSubview:secondViewController.view];?
}?
?
?
在代码中手动创建View并使用代码手动切换
?
- (IBAction)switchToThirdView:(id)sender {?
??? //先创建view?
??? thirdView=[[UIView alloc]?
?????????????? initWithFrame:self.view.bounds];?
??? thirdView.backgroundColor=[UIColor greenColor];?
?
??? //为view增加控件?
??? UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];?
??? button.frame=CGRectMake(100, 100, 100, 100);?
??? [button setTitle:@"回首页"?
??????????? forState:UIControlStateNormal];?
??? [button addTarget:self?
?????????????? action:@selector(exitThirdView:)?
???? forControlEvents:UIControlEventTouchUpInside];?
??? [thirdView addSubview:button];?
?
??? //将view显示出来?
??? //加入动画吧?
??? [UIView beginAnimations:@"flipping view"?
??????????????????? context:nil];?
??? [UIView setAnimationDuration:1];?
??? [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft?
?????????????????????????? forView:self.view?
???????????????????????????? cache:NO];?
??? [self.view addSubview:thirdView];?
??? [UIView commitAnimations];?
}?
?
- (void)exitThirdView:(id)sender?
{?
??? //也加入动画效果?
??? [UIView beginAnimations:@"flipping view"?
??????????????????? context:nil];?
??? [UIView setAnimationDuration:1];?
??? [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight?
?????????????????????????? forView:self.view?
???????????????????????????? cache:NO];?
??? [thirdView removeFromSuperview];?
??? [UIView commitAnimations];?
}?
1 楼 w11h22j33 2012-02-06 在viewDidAppear方法中做了一段页面开始的动画,但是动画效果在横屏是没有问题的,在竖屏轨迹总是不对。