ios学习笔记之UI篇(五):切换视图

来源:互联网 发布:编程入门书籍 编辑:程序博客网 时间:2024/05/18 02:01

首先呢,你要先添加两个视图,纵向和横向视图,具体方法为在你已经创建的单视图工程下,鼠标放在dock上的view图标上,按住option键拖动view图标直到出现绿色加号为视图创建副本,单击dock上新添加的视图,打开属性检查器在顶部的Simulated Metrics中找到orientation弹出菜单将其值从portrait改为landscape,打开辅助编辑器,显示. h文件按住ctrl把纵向视图拖向.h文件创建名为portrait的输出口,拖入按钮调整大小,居中放置,关联按钮的输出口:按住ctrl将横向视图中foo按钮拖向右边头文件将outlet改为outlet collection 命名为foos,将纵向视图foo按钮也与同一输出口关联,对bar按钮重复以上步骤,最后创建动作方法,将四个按钮与之关联。

然后,在.m文件中添加如下代码

#define degressToRadians(x) (M_PI *(x)/180.0)
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{    if (toInterfaceOrientation==UIInterfaceOrientationPortrait) {        self.view=self.portrait;//根据旋转方向设置view属性        self.view.transform=CGAffineTransformIdentity;        self.view.transform=CGAffineTransformMakeRotation(degressToRadians(0));//创建旋转变幻        self.view.bounds=CGRectMake(0.0, 0.0, 320.0, 460.0);    } else if(toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft){        self.view=self.landscape;        self.view.transform=CGAffineTransformIdentity;        self.view.transform=CGAffineTransformMakeRotation(degressToRadians(-90));        self.view.bounds=CGRectMake(0.0, 0.0, 480.0, 300.0);    } else if(toInterfaceOrientation==UIInterfaceOrientationLandscapeRight){        self.view=self.landscape;        self.view.transform=CGAffineTransformIdentity;        self.view.transform=CGAffineTransformMakeRotation(degressToRadians(90));        self.view.bounds=CGRectMake(0.0, 0.0, 480.0, 300.0);    }}

这个方法会在旋转即将开始,实际旋转之前调用,方法中执行的动作作为旋转动画的一部分,接下来实现action的方法

- (IBAction)buttonTapped:(id)sender {    NSString *message=nil;    if ([self.foos containsObject:sender]) {//        message=@"Foo button pressed";        for (UIButton *oneFoo in self.foos) {            oneFoo.hidden=YES;        }    } else {        //message=@"Bar button pressed";        for (UIButton *oneBar in self.bars) {            oneBar.hidden=YES;        }    }    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:message message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];    [alert show];}