Skip to content

Instantly share code, notes, and snippets.

@tomokr
Created November 15, 2013 14:39
Show Gist options
  • Save tomokr/7485302 to your computer and use it in GitHub Desktop.
Save tomokr/7485302 to your computer and use it in GitHub Desktop.
delegateでモーダル画面間の値の受け渡し ref: http://qiita.com/tomokr/items/18d78ed53ac1deb72a39
@protocol つくるDelegate;
@interface つくる: UIViewController{
//もともとあるやつ
}
@property (weak, nonatomic) id<つくるDelegate> delegate;
// イニシャライザ
- (id)init;
//「おくる」側で値をセットするための関数
-(void)セット;
@end //これももともとある
@protocol つくるDelegate <NSObject>
// 「もらう」で呼び出すためのメソッド「おくる」、ここでは送る値はNSString
- (void)おくる:(NSString*)str;
@end
- (id)init
{
if (self = [super init]) {
// 初期処理
}
return self;
}
- (void)せっと {
NSString *str = @"おくる値だよー";
[self.delegate おくる:str];
}
//#importがあるところに追加
#import "つくる.h"
@interface もらう : UIViewController<つくるDelegate>{
//もともとあるところに<>で追加!
}
- (void)おくる:(NSString*)str
{
//受け取った値をlogに表示
NSLog(@"%@", str);
//「つくる」を閉じる
[self dismissViewControllerAnimated:YES completion:NULL];
}
//Storyboardをつかわない編
-(void)いどう{
// 遷移先の「つくる」のインスタンスを取得
つくる *つくる = [[つくる alloc] init];
つくる.delegate = self;
[self presentViewController:つくる animated:YES completion:nil];
}
//Storyboadをつかう編
- (void)いどう:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"つくるをひらく"]) {
//ここは、Storyboardで設定しなければいけないところ。
//ModalでViewController同士をつないで、そのModalの●を選んで、
//IDに「つくるをひらく」と入れた場合です。
つくる *つくる = segue.destinationViewController;
つくる.delegate = self;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment