如果習慣使用純代碼編程的開發者,會感覺使用StoryBoard會非常不舒服,但是看完本教程能讓你快速使用StoryBoard開發。StoryBoard和StoryBoard、StoryBoard和Code視圖控制器、StoryBoard和Xib視圖控制器之間切換和傳值。
一 于StoryBoard相關的類、方法和屬性
1 UIStoryboard
// 根據StoryBoard名字獲取StoryBoard
+ (UIStoryboard *)storyboardWithName:(NSString *)name bundle:(nullab?le NSBundle *)storyboardBundleOrNil;
// 獲取指定StoryBoard的第一個視圖控制器
- (nullable __kindof UIViewController *)instantiateInitialViewController;
// 獲取指定StoryBoard的標識符為identifier的視圖控制器
- (__kindof UIViewController *)instantiateViewControllerWithIdentifier:(NSString *)identifier;
2 UIStoryboardSegue
// 標識符
@property (nullable, nonatomic, copy, readonly) NSString *identifier;
// 源視圖控制器
@property (nonatomic, readonly) __kindof UIViewController *sourceViewController;
// 目的視圖控制器
@property (nonatomic, readonly) __kindof UIViewController *destinationViewController;
3 UIStoryboardUnwindSegueSource
4 UIStoryboardPopoverSegue
5 UIViewController
// 處理標識符為identifier的StoryBoardSegue
- (void)performSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender NS_AVAILABLE_IOS(5_0);
二 動態加載StoryBoard
AppDelegate.m
動態加載StoryBoard,TARGETS設置中Deployment Info 項Main Interface刪除main
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UIViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController];
self.window.rootViewController = vc;
return YES;
}
三 StoryBoard->StoryBoard切換和傳值
圖例1
1 視圖切換
方法一:
圖例2
方法二:
圖例4
// StoryBoard 跳轉到 StoryBoard
- (IBAction)StoryBoardCodePushButton:(id)sender
{
// 已經連線的seg
[self performSegueWithIdentifier:@"Detail" sender:self];
}
2 視圖傳值
// UIViewController 方法 用于處理視圖控制器之間的傳值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([sender isKindOfClass:[UIButton class]])
{
// 方法一,使用KVC給B 也就是目標場景傳值
UIViewController *destinationController=[segue destinationViewController];
[destinationController setValue:@"StoryBoard Segue Push" forKey:@"name"];
}
else
{
// 方法2,使用屬性傳值,需導入相關的類.h
DetailViewController *bController=[segue destinationViewController];
bController.name=@"StoryBoard Code Push";
}
}
四 StoryBoard->Code視圖控制器切換和傳值(Xib視圖控制器原理一樣)
self視圖控制器是用StoryBoard創建的
// StoryBoard 跳轉到 Code
- (IBAction)StoryBoardtoCodeVCPush:(id)sender
{
CodeViewController *vc = [[CodeViewController alloc] init];
vc.name = @"StoryBoard to CodeVC Push";
[self.navigationController pushViewController:vc animated:YES];
}
五 Code視圖控制器->StoryBoard切換和傳值(Xib視圖控制器原理一樣)
圖例3
self視圖控制器是用Code(Xib)創建的
- (void)barButton
{
// 從Code視圖控制器跳轉到StoryBoard中的視圖控制器 (Xib原理一樣)
UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
DetailViewController *vc = [story instantiateViewControllerWithIdentifier:@"VC"];
vc.name = @"Code to StoryBoard Push";
[self.navigationController pushViewController:vc animated:YES];
}