2011-10-20 7 views
1

私はサブビューとしてUIViewUIViewControllerを持っています。私は、UIViewControllerUIViewの特定のアクションを通知(または聞いてください)したいと思います。 これを行うための標準的な方法は何ですか?サブビューで起こったことについてUIViewControllerに伝えてください

+1

どのような操作ですか?ボタンを押す?プロパティの値の変更はありますか? –

+0

もちろん、ボタンを押しても機能します。 – SundayMonday

答えて

2

あなただけのアクションハンドラがしたい場合は、次の詳細情報については

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // ...... 
    UIButton *myButton = [[UIButton alloc] init]; // or initWithSOMETHING 
    [myButton addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:myButton]; 
    [myButton release]; 
    // ...... 
} 

- (void)someMethod:(id)sender { 
    if (![sender isKindOfClass:[UIButton class]]) return; 
    // Do something about the action here... 
} 

を、UIControl Documentationを参照してください。

アクションメッセージ

– sendAction:to:forEvent: 
– sendActionsForControlEvents: 
– addTarget:action:forControlEvents: 
– removeTarget:action:forControlEvents: 
– actionsForTarget:forControlEvent: 
– allTargets 
– allControlEvents 

を準備し、送信します

それとも、あなたは親ビューコントローラを呼び出してビューコントローラの話ならば、あなたは「親」ビューコントローラへのアクセスにUIViewControllerpresentingViewControllerプロパティを使用できます。

UIViewController *parentVC = [self presentingViewController]; 
[parentVC setSomething:self.withSomething]; 

presentingViewController - ビューをこのビューコントローラを提示したコントローラ。このプロパティの(読み取り専用)

@property(nonatomic, readonly) UIViewController *presentingViewController

議論
デフォルトの実装では、このビューコントローラから出発して、ビュー 階層を歩きます。最初のビュー コントローラはそれが presentViewController:animated:completion:方法を受け見つけ、またはそのプロパティの 値として返されるYESに設定さ definesPresentationContext性質を有しています。それは、 が戻り値を見つけるか、ルートビューコントローラに到達するまで階層を歩き続けます。


それともUIViewsuperviewプロパティ:

superview

[self.view.superview doSomething]; 
- 受信機のスーパー、またはそれが何を持っていない場合はnil。 (読み取り専用)
@property(nonatomic, readonly) UIView *superview

2

上記のコメントにあなたの答えに基づいて、これはボタンの押しであることを、「標準」の方法は、Uicontrolの中のメカニズムを使用することです。方法myViewController上で実行する:あなたは「myButtonという」を押すと

[myButton addTarget:myViewController action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

を行うのであれば、プログラムで、「のbuttonPressedは」原因となります。 Interface Builderを使用して接続することもできます。

このコードは、UIViewControllerのUIView内のさまざまな場所に配置することができ、その結果、変数の正確な名前が変更されますが、押されたボタンを処理するにはおそらく最も簡単な方法です。

関連する問題