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

來源:互聯網
上載者:User

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

 

準備工作
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的方式進行賦值

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.