27

私は最近、Xcode 内で MainStoryboard.storyboard を操作しようとしましたが、これまでのところかなりうまくいっています。いくつかのコードで遊んでいるときに障害にぶつかりましたが、これを解決する方法がわかりません。

新しいViewControllerを割り当てて初期化するとき(ViewControllersクラスで宣言したカスタムinitを使用)、次のようにします。

ViewController *myViewController = [[ViewController alloc] initWithMyCustomData:myCustomData];

その後、次のようなことができます:

[self presentViewController:myViewController animated:YES completion:nil];

ストーリーボードで作業しているときに、スタンドアロンの ViewController に切り替えるには識別子が必要であることを知りました。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
[self presentViewController:myViewController animated:YES completion:nil];

ストーリーボードを利用しながら、myViewController のカスタム初期化を引き続き使用するにはどうすればよいですか?

次のようなことをしても大丈夫ですか?

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
myViewController.customData = myCustomData;
[self presentViewController:myViewController animated:YES completion:nil];




//MyViewController.m
- (id) initWithMyCustomData:(NSString *) data {
if (self = [super init]) {
    iVarData = data;
}
return self;
}
4

3 に答える 3

17

-init メソッドでビューコントローラーをインスタンス化できます。

 - (instancetype)init
 {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

   self = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];

   if(self)
   {
    //default initialization

   }
   return  self;
 }

そして、あなたのカスタムinitメソッドで

 - (instancetype)initWithImages:(NSArray *)images
 {
   self = [self init];

   if(self)
   {
     self.images = images;
   }

   return  self;
 }
于 2016-02-25T06:41:11.870 に答える