准備工作
Storyboard上為一個ViewController拖拽兩個子控制器,並且設置兩個segue的identifier分別為childvc1,childvc2
效果
#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
兩點要注意
prepareForSegue在這裡要早於viewDidLoad被調用 使用weak引用是為了不參與子控制器的生命周期
#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的動態特性
因為子控制器的屬性名稱與segue.identifer一致,所以只需要判斷respondsToSelector:NSSelectorFromString(segue.identifier)就知道當前是不是為對應的子控制器來prepareForSegue 這裡的 respondsToSelector:NSSelectorFromString(segue.identifier)就是是否含有對應的get方法 通過KVC的方式進行賦值