IOS开发(十一):场景(3)模态切换示例

在本示例中,开发一个通过可视化的方法进行各个视图之间切换的方法。

一、创建项目

新建一个Empty Application,名为Scene_Test2;

打开AppDelegate.m文件,删除方法didFinishLaunchingWithOptions中的代码,只剩下"return YES;"语句;

创建一个Storyboard:在菜单中选择File->New->New File,在左边选择IOS的User Interface,在右边选择Storyboard,在下一步中输入名称为MainStoryboard,选择好Group,单击Create创建完成;

配置程序,使程序从MainStoryboard启动:单击Xcode左边带有蓝色图标的项目名Scene_Test2,选择Summary,在Main Storyboard中选择MainStoryboard(我们创建的storyboard)。这样当程序运行的时候,就从MainStoryboard加载内容了。

二、添加Navigation Controller和Tabel View Controller

1、单击MainStoryboard.storyboard,会发现编辑区域是空白的。拖动一个Navigation Controller到编辑区域,如图所示:

选中右边的那个View Controller,按Delete键删除,然后拖动一个Tabel View Controller到编辑区域,如图所示:

2、现在将在这个Tabel View Controller中创建静态表格,不过先要将其设置为左边Navigation Controller的Root Controller:

选中Navigation Controller,按住Control键,向右边的Tabel View Controller拉线;松开鼠标,在弹出的菜单中选择如下图所示的选项后,两个框之间就会出现一条连线:这个就可以称作Segue。

3、选中Tabel View Controller的Table View,在属性中设置其Content属性为Static Cells,这时候会变成3行Cell样式的Table View:

    

4、设置行数:

选中Tabel View Section,设置其属性为2,则变成2行:

5、设置每行的样式:

选中每一行,设置Style属性为Basic;并且可以修改Label属性,比如第一个设置为Date and Time,默认是Title。

6、选中Navigation Item,在属性中设置Title为Root View,BackButton为Root:

    

三、实现单击表格中的行进行页面转换,并且在新页面上显示当前切换的时间

1、在菜单中选择File->New->New File,选择IOS的Cocoa Touch,选择一个Objective C class文件(有的是选择UIViewController subclass,但是我的Xcode并没有看到),命名为DateAndTimeViewController:

2、再次打开MainStoryboard,拖动一个View Controller到编辑区域,选中这个View Controller,在属性设置中,设置Class属性为刚才创建的DateAndTimeViewController。这样就可以向DateAndTimeViewController创建映射了。

在新创建的View Controller中添加几个Label, 并且设置输出口,分别命名为dateLabel和timeLabel。

选中DateAndTimeViewController中的Navigation Item,在属性中设置其Title为Date Time。

打开DateAndTimeViewController.m文件,添加如下代码:

//每次切换到这个视图,显示当前的日期和时间
-(void)viewWillAppear:(BOOL)animated{
    NSDate *now = [NSDate date];
    dateLabel.text = [NSDateFormatter
                      localizedStringFromDate:now
                      dateStyle:NSDateFormatterLongStyle
                      timeStyle:NSDateFormatterNoStyle];
    timeLabel.text = [NSDateFormatter
                      localizedStringFromDate:now
                      dateStyle:NSDateFormatterNoStyle
                      timeStyle:NSDateFormatterLongStyle];
}

3、打开MainStoryboard,选中表格的第一行,按住Control,向View Controller拉线,在弹出框中选择push。 
    这样Root View Controller与DateAndTimeViewController之间就出现了小箭头,运行时点击该行,就会切    换到下一页。

运行程序,如图所示:

    

原文地址:https://www.cnblogs.com/xsjayz/p/3012644.html