码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 获取Interface Builder上的子控制器的两种方式

时间:2015-05-17 15:19:50      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:ios   ib   子控制器   child   controller   

原创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

两点要注意

  1. prepareForSegue在这里要早于viewDidLoad被调用
  2. 使用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的动态特性

  1. 因为子控制器的属性名称与segue.identifer一致,所以只需要判断respondsToSelector:NSSelectorFromString(segue.identifier)就知道当前是不是为对应的子控制器来prepareForSegue
  2. 这里的 respondsToSelector:NSSelectorFromString(segue.identifier)就是是否含有对应的get方法
  3. 通过KVC的方式进行赋值

iOS 获取Interface Builder上的子控制器的两种方式

标签:ios   ib   子控制器   child   controller   

原文地址:http://blog.csdn.net/hello_hwc/article/details/45788581

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!