最新Xcode 4.3.2 下使用Storyboard和ARC开发iPhone4程序 03——Storyboard类及使用

来源:互联网 发布:java中如何声明变量 编辑:程序博客网 时间:2024/06/05 22:42
一、Storyboard类介绍

   Storyboard是你可以用来定义用户界面的一种新的方式,像xib。与xib不同的是它可以同时管理多个ViewController,而且可以在Storyboard中配置ViewController 之间的跳转关系。

   如果主窗口只有一个viewcontroller是作为storyboard的第一个界面,就需要勾选上Initial Scene

story boardxcode4.2新增的一个特性,它将原有工程中的所有xib文件集成在一起,用拖拽的方式建立起两个viewController之间的跳转关系,使得整个程序的UI跳转逻辑清楚明了。使用storyboard后,界面相关的代码编写将更少。

简单说一个storyboard是个什么东西。storyboard引入了两个概念:

scene:一个场景,由一个viewController和相关的xib表示

     segue: ['seiɡwei] n. 继续,持续。用于连接scenessegue有多种类型,包括:

               Push, Modal, Popover and more

               segue也负责传递数据和返回数据。

整个程序的界面转换就是在scene之间切换。界面跳转关系,比如按哪个键跳到哪个界面,由segue来描述。segue也可以带数据,以便做数据传递。据说苹果的这种设计方案是抄的AdobeFlash,具体不得而知。

1UIStoryboard

此类继承于NSObject,共有三个方法,一个类方法,两个实例方法

1)得到一个StoryBoard Object对象:类方法

+ (UIStoryboard*)storyboardWithName:(NSString*)name bundle:(NSBundle*)storyboard

BundleOrNil;

//也可以通过一个在storyboard中有sceneviewController中用self.storyBoard得到自己所在的storyboard对象。

2)接口

- (id)instantiateInitialViewController;

//返回第一个界面(根视图所在界面),每个storyboard必须有一个入口界面,特别是程序的主storyboard的第一个界面,就是程序的主界面。

 

- (id)instantiateViewControllerWithIdentifier:(NSString*)identifier;

// storyboard相应标识对应的界面。如果identifier不存在或者为nil,引发异常。

2UIStoryboardSegue类,同样此类继承于NSObject

两个界面之间的转换,转换之前调用当前viewcontrollerprepareForSegue:sender: 函数(这里可以处理一些数据赋值之类).可以通过生成子类来自定义转换动画.

-(void)prepareForSegue:(UIStoryboardSegue *)seguesender:(id)sender{

}

1)属性

@property(nonatomic, readonly) id destinationViewController // (read-only)

@property(nonatomic, readonly)NSString *identifier   // (read-only)

@property(nonatomic, readonly) id sourceViewController  // (read-only)

2)初始化,此类公有一个实例方法

- (id)initWithIdentifier:(NSString *)identifier source:(UIViewController *)sourcedestination:(UIViewController*)destination;

3UIStoryboardPopoverSegue类。此类继承于UIStoryboardSegue :NSObject

此类只有一个属性:

@property(nonatomic, retain, readonly)UIPopoverController*popoverController;

4、动画

- (void)perform//子类重写来自定义转换动画

@property(nonatomic, retain, readonly)UIPopoverController*popoverController;

 

二、Storyboard使用

如果你是创建新项目,Xcode模版可以提供一个配置好的Storyboard供你使用。对于其它的应用,使用Storyboard的过程如下:

1、配置应用程序Info.plist文件

·        添加UIMainStoryboardFile ,值为storyboard的文件名。

·        删除原来的NSMainNibFile

2、像以前创建xib文件一样创建一个storyboard文件

3、配置storyboard中的viewController

三、Storyboard的创建

  你可以用InterfaceBuilder 去为你的应用程序创建一个Stroyboard,一般来说一个应用使用一个Storyboard就够了,但是如果你想创建多个也是可以的,只要你愿意。一个 Stroyboard应该至少含有一个ViewController

  iPhone中,对于每一个在StoryboardViewController都管理着一个scene,每个scene又管理着screen上的东东,但对于iPad来说,多个scene可以同时呈现在一个screen上。你可以从library中拖拽viewController到你的Storyboard上。

  当你想关联两个viewController时,你可以按着control键,用鼠标从一个ViewController中的button,table view cell…拖拽连接到另一个你想跳转到的ViewController,这样就创建了一个segue,不要忘记设置identifier哦。

四、Scene之间的数据传递

 当你从当前 scene中触发一个segue的时候,系统会自动调用prepareForSegue:sender:这个方法。如果你想从一个界面切换到里另一个界面的时候传递数据,你应该override这个方法。

五、ViewController之间的跳转

如果在 Storyboard中,要实现当前的 ViewController和要跳转到另一个ViewController。分两种情况:

1、连接场景segue存在。如果在Storyboard中当前的 ViewController和要跳转的ViewController之间的segue存在,则可以执行performSegueWithIdentifier:sender:这个方法实现跳转。

2、连接场景segue不存在。如果目标ViewController存在Storyboard中,但是没有segue。你可以通过UIStoryboardinstantiateViewControllerWithIdentifier:这个方法获取到它,然后再用你想要的方式实现跳转,如:压栈。

3、如果目标ViewController不存在在Storyboard中,那就先去创建它吧。

六、小结

根据上面的UIStoryBoard类知道,可以简单的把storyboard当成以前的nib文件使用,只不过他是一个合集,读取文件用另一种自己的函数就行了。正常的使用当然是灵活运用UIStoryboardSegue。它可以关系两个controller,关系一个controller中的控件到另一个controller中,还可以自定义一些动画。

七、实例

接下来的例子主要显示Storyboard的功能,主要实现如下图所示,顺便用Storyboard实现了静态表格和动态表格等功能。


为了显示Storyboard的功能,我们从Empty Application开始我们的例子。

1、运行Xcode 4.3.2,新建一个Empty Application,名称为DemoSBTableViewTest


2、打开BIDAppDelegate.m,找到didFinishLaunchingWithOptions方法,删除其中代码,使得只有return YES;语句。


3、创建一个Storyboard

在菜单栏依次选择File — New — NewFile,在弹出的窗口,左边选择iOS组中的User Interface,右边选择Storyboard

之后单击Next,选择Device FamilyiPhone,单击Next,输入名称MainStoryboard,并设好Group

单击Create,这样就创建了一个Storyboard

4、配置程序,使得从MainStoryboard启动:

先单击左边带蓝色图标的DemoSBTableViewTest,然后选择Summary,接下来在Main Storyboard中选择MainStoryboard


这样,当运行程序时,就从MainStoryboard加载内容了。

5、单击MainStoryboard.storyboard,会发现编辑区域是空的。拖一个NavigationController到编辑区域:


7、我们将在这个Table ViewController中创建静态表格,

8、选中Table ViewController中的Table View,之后打开AttributeInspector,设置其Content属性为Static Cells

这样你会发现Table View中出现了三行Cell。在上图你可以设置很多熟悉,比如StyleSection数量等。

9、设置行数:

选中Table View Section,在AttributeInspector中设置其行数为2

然后选中每一行,设置其StyleBasic

设置第一行中Label的值为:Date and Time,第二行中的LabelTitle List;之后选中下方的Navigation Item,在AttributeInspector设置TitleRoot ViewBack ButtonBack Root

10、我们实现单击表格中的Date and Time这一行实现页面转换,在新页面显示切换时的时间。

在菜单栏依次选择File — New — NewFile,在弹出的窗口左边选择iOS中的Cocoa Touch,右边选择UIViewControllersubclass

单击Next,输入名称BIDDateAndTimeViewController,但是不要选XIB

之后,选好位置和Group,完成创建。

11、再次打开MainStoryboard.storyboard,拖一个View Controller到编辑区域,然后选中这个View Controller,打开Identity Inspector,设置class属性为BIDDateAndTimeViewController

这样,我们就可以向DateAndTimeViewController创建映射了。

12、向新拖入的View Controller添加控件,如下图:

然后将显示为Label的两个标签向DateAndTimeViewController.h中创建映射,名称分别是dateLabeltimeLabel


13、打开DateAndTimeViewController.m,在ViewDidUnload方法之后添加代码:

//每次切换到这个试图,显示切换时的日期和时间

- (void)viewWillAppear:(BOOL)animated {

   NSDate *now = [NSDatedate];

   dateLabel.text = [NSDateFormatter

                     localizedStringFromDate:now

                     dateStyle:NSDateFormatterLongStyle

                     timeStyle:NSDateFormatterNoStyle];

   timeLabel.text = [NSDateFormatter

                     localizedStringFromDate:now

                     dateStyle:NSDateFormatterNoStyle

                     timeStyle:NSDateFormatterLongStyle];

}

14、打开MainStoryboard.storyboard,选中表格的行Date and Time,按住Contrl,向View Controller拉线:在弹出的菜单选择Push


这样,Root ViewControllerBIDDateAndTimeViewController之间就出现了箭头,运行时当点击表格中的那一行,视图就会切换到BIDDateAndTimeViewController

15、选中BIDDateAndTimeViewController中的Navigation Item,在AttributeInspector中设置其TitleDate and Time

16、运行一下,首先程序将加载静态表格,表格中有两行:Date and Time以及Title List,单击Date and Time,视图切换到相应视图,单击左上角的Back Root按钮,视图回到Root View。每次进入Date and Time视图,显示的时间都会不同:

 

17、接下来,我们将要实现,单击Title List行,显示一个表格,并且单击表格中的某一行,我们可以在新弹出的视图中编辑该行内容。首先创建ViewController文件:BIDListViewControllerBIDListEditViewController,前者继承UITableViewController,后者继承UIViewController,参照第10步。都不要创建XIB文件。

然后打开MainStoryboard.storyboard,拖一个Table ViewControllerView Controller到编辑区域,调整所有视图在编辑区域的位置,如下图:

设置新拖入的Table ViewControllerView Controllerclass属性分别是BIDListViewControllerBIDListEditViewController,参考第11步。

18、参照第14步,从Root ViewController中的Title List那一行向BIDList ViewController拉线,并在弹出菜单也选择Push。然后选中BIDList ViewControllerNavigation Item,设置TitleTitle ListBack ButtonBack,可以参照第9步。

19、向BIDList ViewController中的表格区域拖入一个Table View Cell,这样其中就有两个Cell了。设置第一个CellIdentifier属性为GreenIdentifier。同样对第二个Cell进行设置,Identifier属性为RedIdentifier

20、打开BIDListViewController.m,向其中添加代码:

20.1#import的下一行添加代码:

#import"BIDListViewController.h"

@interfaceBIDListViewController ()//这里可以定义属性,不需要前置声明定义了

@property(strong, nonatomic)NSMutableArray *listArray;

@property(copy, nonatomic)NSDictionary *editedSelection;

@end

 

@implementationBIDListViewController

@synthesizelistArray;

@synthesizeeditedSelection;

20.2@implementation之后添加代码:

@synthesizelistArray;

@synthesizeeditedSelection;

20.3找到viewDidLoad方法,向其中添加代码:

- (void)viewDidLoad

{

   [superviewDidLoad];

   NSMutableArray *array =[[NSMutableArrayalloc] initWithObjects:@"Horse",@"Sheep",@"Pig",@"Dog",@"Cat",@"Chicken",@"Duck",

@"Goose",@"Tree",@"Flower",@"Grass",@"Fence",@"House",@"Table",@"Chair",

@"Book",@"Swing",nil];

   self.listArray = array;

   // Uncomment the following line topreserve selection between presentations.

   //self.clearsSelectionOnViewWillAppear = NO;

 

   // Uncomment the following line todisplay an Edit button in the navigation bar for this viewcontroller.

   //self.navigationItem.rightBarButtonItem =self.editButtonItem;

}

找到viewDidUnLoad方法,向其中添加self.listArray = nil;代码

20.4找到numberOfSectionsInTableView方法,使其返回1,并删掉#warning

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView

{

//#warning Potentially incompletemethod implementation.

   // Return the number ofsections.

   return1;

}

20.5找到numberOfRowsInSection方法,删掉#warning,使其返回[listArray count]

- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:

(NSInteger)section

{

//#warning Incomplete methodimplementation.

   // Return the number of rows in thesection.

   return [listArraycount];

}

20.6找到cellForRowAtIndexPath方法,修改其中代码:

- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:

(NSIndexPath *)indexPath

{

   //static NSString *CellIdentifier =@"Cell";

  // UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];

   // Configure thecell...

   NSUInteger row = [indexPathrow];

   NSString *identifier =nil;

   if (row%2 ==0){

       identifier =@"GreenIdentifier";

   }else

       identifier =@"RedIdentifier";

   UITableViewCell *cell =[tableViewdequeueReusableCellWithIdentifier:identifier];

   UILabel *cellLabel =(UILabel *)[cell viewWithTag:1];

   if (row%2 ==0){

       cellLabel.textColor =[UIColorredColor];//设置字体的redColor颜色

   }else

       cellLabel.textColor =[UIColorgreenColor];//设置字体的greenColor颜色 

   cellLabel.text = [listArrayobjectAtIndex:row];

   

   return cell;

}

21、运行一下,当单击TitleList行时,页面切换到我们List视图:

  

22、下面实现单击List表格中的某一行,视图切换,并且视图中的内容与之前选中的行相关,然后可以对其进行编辑,返回后,原来的数据也会发生改变。

打开MainStoryboard.storyboard,仿照第14步,从BIDList ViewController中的两行向BIDList Edit ViewController拉线,在弹出菜单选择Push

这样BIDList Edit ViewController视图中就出现了Navigation Item,选中它,设置TitleEdit。这样,单击List表格中的某一行,视图都会切换到BIDList Edit ViewController

23Scene之间的数据传递

 当你从当前 scene中触发一个segue的时候,系统会自动调用prepareForSegue:sender:这个方法。如果你想从一个界面切换到里另一个界面的时候传递数据,你应该override(复写)这个方法。

打开BIDListViewController.m,在@end之前添加代码:

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender {

   //获取目的ViewController

   UIViewController *destination = [segue destinationViewController];

   if ([destination respondsToSelector:@selector(setPreViewController:)])

   {

       //自身传递给目ViewController

       [destinationsetValue:selfforKey:@"preViewController"];

   }

   if ([destination respondsToSelector:@selector(setSelection:)])

   {

       //目的ViewController中的selection性存储的是需要编辑的内容及在表格中的位置

       NSIndexPath *indexPath = [self.tableViewindexPathForCell:sender];

       idobject= [self.listArrayobjectAtIndex:indexPath.row];

       NSDictionary *selection = [NSDictionary dictionaryWithObjectsAndKeys:indexPath,@"indexPath",object,@"object",nil];

       [destinationsetValue:selection forKey:@"selection"];

   }

}

ViewDidUnload方法之后添加代码:

- (void)setEditedSelection:(NSDictionary *)dict

{

   if (![dictisEqual:editedSelection])

   {

       editedSelection =dict;

       NSIndexPath *indexPath = [dictobjectForKey:@"indexPath"];

       id newValue = [dictobjectForKey:@"object"];

       [listArrayreplaceObjectAtIndex:indexPath.rowwithObject:newValue];

       [self.tableViewreloadRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

   }

}

24、打开MainStoryboard.storyboard,找到Edit视图,向其中拖一个Text Field和一个标签,标签名设为Edit

然后为这个Text FieldBIDListEditViewController.h中创建Outlet映射,名称为editText

25、打开ListEditViewController.h,向其中添加属性:

#import<UIKit/UIKit.h>

@interfaceBIDListEditViewController :UIViewController

@property(copy,nonatomic) NSDictionary *selection;

@property(weak,nonatomic) id preViewController;

@property(weak,nonatomic) IBOutletUITextField *editText;

 

@end

26、打开ListEditViewController.m,添加代码:

26.1@implementation的下一行添加代码:

@synthesize preViewController;
@synthesize selection;

26.2找到ViewDidLoad方法,它默认是被注释掉的,去掉其周围注释符,添加代码如下:

- (void)viewDidLoad

{

   [superviewDidLoad];

        // Do any additional setup afterloading the view.

   editText.text = [selection objectForKey:@"object"];

   [editTextbecomeFirstResponder];

}26.3ViewDidUnload方法之后添加代码:

- (void)viewWillDisappear:(BOOL)animated

{

   [superviewWillDisappear:animated];

   

   if ([preViewControllerrespondsToSelector:@selector(setEditedSelection:)])

   {

       //结束编辑

       [editTextendEditing:YES];

       NSIndexPath *indexPath =[selection objectForKey:@"indexPath"];

       id object =editText.text;

       NSDictionary *editedSelection =[NSDictionary dictionaryWithObjectsAndKeys:indexPath,@"indexPath",object,@"object",nil];

       //设置上一个ViewController中的editedSelection,由于设置editedSelection方法

       //已经重写,从而对应在表格中的数据会发生变化

       [preViewControllersetValue:editedSelection forKey:@"editedSelection"];

   }

}

27、运行:

   

单击Title List行时,视图切换到上面右图所示。然后单击Pig那一行,视图切换到Edit视图,然后编辑内容,点击Back之后返回,这样,原来表格中的Pig内容就会发生改变成“Pig中文”了:

  

原代码下载地址:

http://m1.mail.sina.com.cn/apps/netdisk/download.php?id=4f74ced1967ce5bbb07683ba72d2c97e

今天就到这里,欢迎提建议! 

转自http://blog.sina.com.cn/s/blog_5a6efa3301016z4n.html

原创粉丝点击