2012-03-05 8 views
0

モーダルビューコントローラからメインビューコントローラでアクション(changeMainNumber)を呼び出そうとしています。アクションは、私が持っている、ViewController.h 2.にUILabel mainNumberを変更する必要があります。XCode:モーダルビューからのメインビューの呼び出しアクション

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController { 

IBOutlet UILabel *mainNumber; 

} 
@property (nonatomic, retain) UILabel *mainNumber; 

-(IBAction)changeMainNumber; 

ViewController.m:

#import "ViewController.h" 

@implementation ViewController 
@synthesize mainNumber; 

- (IBAction)changeMainNumber:(id)sender { 
mainNumber.text = @"2"; 
} 

を次のビューコントローラは、モーダルビューコントローラです。 ModalViewController.h:

#import <UIKit/UIKit.h> 

@class ViewController; 

@interface ModalViewController : UIViewController { 

} 

-(IBAction)callChangeMainNumber:(id)sender; 

とModalViewController.m:この設定で

#import "ModalViewController.h" 

@implementation ModalViewController 

- (IBAction)callChangeMainNumber { 
ViewController *viewController = [[ViewController alloc] init]; 
[viewController changeMainNumber]; 
} 

アプリはcallChangeMainNumberが呼び出されると、私が間違っているかを把握することができないときクラッシュし。あなたが提供できるどんな助けもありがとう!

+0

クラッシュ?メッセージは何ですか?それはどこでクラッシュするのですか?あなたはcallChangeMainNumberの中に新しいViewControllerを作成してそれを変更することを知っていますか? – fbernardo

+0

答えをありがとう。 callChangeMainNumberアクションが実行されると、アプリケーションがクラッシュします(四角形の丸ボタン)。私は何をすべきか正確にはわからないので、changeMainNumberをcallChangeMainNumberで呼び出す正しい方法は何でしょうか? – potato

+0

callChangeMainNumberを実行するとどういう意味ですか?どの線?正しい方法は、ViewControllerオブジェクトをModalViewControllerオブジェクトに渡して、最後のオブジェクトがchangeMainNumberメッセージを最初のオブジェクトに送信できるようにすることです。とった? – fbernardo

答えて

1

ModalViewControllerから投稿したコードがViewControllerを参照していません。コード内に新しいものを作成しています。あなたの問題を解決する最善の方法は、ViewControllerをModalViewControllerの代理人にすることです。

あなたのModalViewController.hファイルでは、このコードを@implementationの上に置く必要があります。ヘッダーのあなたの@implementationで次に

@protocol ModalViewControllerDelegate 
    - (void)shouldChangeMainNumber; 
@end 

は持っている:
@property (nonatomic,assign)IBOutlet id <ModalViewControllerDelegate> delegate; 

は今、あなたはあなたのIBActionメソッドを持っている.mファイルで、あなたはそれがメインの番号を変更したいデリゲートを教えてください。

- (IBAction)callChangeMainNumber { 
    [self.delegate shouldChangeMainNumber]; 
} 

その後、あなたのViewController.mファイルで使用すると、通常のviewDidLoadで、ModalViewControllerのデリゲートとして自分自身を設定する必要があるが、それを置くのに良い場所です。だからまずModalViewControllerのヘッダーにプロパティを作成して合成し、次にこれをviewDidLoadに追加します。あなたの.mファイルにデリゲートメソッドを実装する必要が

self.modalViewController.delegate = self; 

、最終的にはどこか

- (void)shouldChangeMainNumber { 
    mainNumber.text = @"2"; 
}