你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 獲取Interface Builder上的子控制器的兩種方式

iOS 獲取Interface Builder上的子控制器的兩種方式

編輯:IOS開發綜合

 


准備工作
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的方式進行賦值
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved