iOS 擷取Interface Builder上的子控制器的兩種方式,iosbuilder
原創Blog,轉載請註明出處
blog.csdn.net/hello_hwc
準備工作
Storyboard上為一個ViewController拖拽兩個子控制器,並且設定兩個segue的identifier分別為childvc1,childvc2
效果
方式一,根據segue的identifier來判斷獲得
#import "ViewController.h"#import "ChildViewController1.h"#import "ChildViewController2.h"@interface ViewController ()@property (weak,nonatomic)ChildViewController1 * childvc1;@property (weak,nonatomic)ChildViewController2 * childvc2;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.childvc1.view.backgroundColor = [UIColor blueColor]; self.childvc2.view.backgroundColor = [UIColor greenColor]; // Do any additional setup after loading the view, typically from a nib.}-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:@"childvc1"]) { self.childvc1 = segue.destinationViewController; } if ([segue.identifier isEqualToString:@"childvc2"]) { self.childvc2 = segue.destinationViewController; }}@end
兩點要注意
方式二,藉助KVC的特性,建立一些通用的代碼
#import "ViewController.h"#import "ChildViewController1.h"#import "ChildViewController2.h"@interface ViewController ()@property (weak,nonatomic)ChildViewController1 * childvc1;@property (weak,nonatomic)ChildViewController2 * childvc2;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.childvc1.view.backgroundColor = [UIColor blueColor]; self.childvc2.view.backgroundColor = [UIColor greenColor]; // Do any additional setup after loading the view, typically from a nib.}-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([self respondsToSelector:NSSelectorFromString(segue.identifier)]) { [self setValue:segue.destinationViewController forKey:segue.identifier]; }}@end
注意,這裡的
segue的identifier一定要和聲明的對應子控制器的屬性一致。
原理-利用KVC的動態特性