原创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
两点要注意
- prepareForSegue在这里要早于viewDidLoad被调用
- 使用weak引用是为了不参与子控制器的生命周期
方式二,借助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的动态特性
- 因为子控制器的属性名称与segue.identifer一致,所以只需要判断respondsToSelector:NSSelectorFromString(segue.identifier)就知道当前是不是为对应的子控制器来prepareForSegue
- 这里的 respondsToSelector:NSSelectorFromString(segue.identifier)就是是否含有对应的get方法
- 通过KVC的方式进行赋值
时间: 2024-10-18 03:11:36