代表 – 如何使用?

我想我理解代表背后的逻辑。 我使用它的问题更多了。 涉及多少步骤? 我是否必须使用现有代表? 或者我可以使用我的一个吗?

在我的例子中,我得到了AppDelegate,它创建了许多相同类型的视图(对象/视图控制器)。 每个视图都应以某种方式调用AppDelegate上的方法来关闭它自己。 触摸视图中的按钮时会发生这种情况。 方法调用将包括视图的引用(self)。

到目前为止,我从其他语言中了解响应者,事件监听器等。 它们使用起来非常简单。

有谁能够帮助我。 我刚刚在网上找到了大量代码,其中包含大量代码。 在Objective C中调用父级并不难。

我认为你应该使用NSNotificationCenter

在你AppDelegate.m

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonPushed:) name:@"ButtonPushedNotification" object:nil]; } - (void)applicationWillTerminate:(UIApplication *)application { ... ... [[NSNotificationCenter defaultCenter] removeObserver:self]; } 

这是通知发生时将调用它的选择器(我们仍然在AppDelegate.m中

 - (void)buttonPushed:(NSNotification *)notification { NSLog(@"the button pushed..."); } 

按下按钮(在方法内)时,在ViewController.m中 ,您应该发布如下通知:

 { ... [[NSNotificationCenter defaultCenter] postNotificationName:@"ButtonPushedNotification" object:nil]; ... } 

你可以创建自己的:

在MyView1.h中:

 @class MyView1; @protocol MyView1Delegate  - (void)closeMyView1:(MyView1 *)myView1; @end @interface MyView1 : NSObject { id _delegate; } @property (assign, nonatomic, readwrite) id delegate; ... @end 

在MyView1.m中:

 @interface MyView1 @synthesize delegate = _delegate; ... // The method that tells the delegate to close me - (void)closeMe { .... if ([_delegate respondsToSelector:@selector(closeMyView1:)]) { [_delegate closeMyView1:self]; } } @end 

在AppDelegate.h中:

 #import "MyView1.h" @interface AppDelegate  { MyView1 *_myView1; } ... @end 

在AppDelegate.m中:

 - (void)someCreateViewMethod { _myView1 = [[MyView1 alloc] initWithFrame:NSMakeRect(0, 0, 100, 200)]; [_myView1 setDelegate:self]; ... } 

获得所需内容的简单方法是从一个视图开始。 然后,以模态方式呈现每个其他视图。 当按下视图中的按钮时

[self dismissModalViewControllerAnimated:YES];

这是我刚刚开始进行iPhone开发时可能会帮助你的代表们的事情

 Delegates //In parent .m file: //assign the delegate - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"segueName"]) { childController *foo = segue.destinationViewController; foo.delegate = self; } } //implement protocol method(s): - (void) methodName:(dataType*) dataName { //An example of what you could do if your data was an NSDate buttonLabel.titleLabel.text = [[date description] substringToIndex:10]; } //In parent .h file: //import child header #import "ChildName.h" //indicate conformity with protocol @interface ParentName : UIViewController  //In child .h file //declare protocol @protocol ChildNameDelegate - (void) methodName:(dataType*) dataName; @end //declare delegate @property (unsafe_unretained, nonatomic) id delegate; //In child .m file //synthesize delegate @synthesize delegate; //use method - (IBAction)actionName:(id)sender { [delegate methodName:assignedData]; }