我想我理解代表背后的逻辑。我使用它的问题更多了。涉及多少步骤?我是否必须使用现有代表?或者我可以使用我的那个吗?
在我的示例中,我得到了AppDelegate,它创建了许多相同类型的视图(对象/视图控制器)。每个视图都应该以某种方式调用AppDelegate上的方法来关闭它自己。触摸视图中的按钮时会发生这种情况。方法调用将包括视图的引用(self)。
到目前为止,我从其他语言中了解响应者,事件监听器等。它们使用起来非常简单。
任何人都可以帮助我。我刚刚在网上找到了大量代码,其中包含大量代码。在Objective C中调用父项很难。
答案 0 :(得分:1)
获得所需内容的简单方法是从一个视图开始。然后,以模态方式呈现每个其他视图。按下视图中的按钮时
[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 <ChildNameDelegate>
//In child .h file
//declare protocol
@protocol ChildNameDelegate
- (void) methodName:(dataType*) dataName;
@end
//declare delegate
@property (unsafe_unretained, nonatomic) id<ChildNameDelegate> delegate;
//In child .m file
//synthesize delegate
@synthesize delegate;
//use method
- (IBAction)actionName:(id)sender
{
[delegate methodName:assignedData];
}
答案 1 :(得分:1)
您可以创建自己的:
在MyView1.h中:
@class MyView1;
@protocol MyView1Delegate <NSObject>
- (void)closeMyView1:(MyView1 *)myView1;
@end
@interface MyView1 : NSObject
{
id<MyView1Delegate> _delegate;
}
@property (assign, nonatomic, readwrite) id<MyView1Delegate> 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 <MyView1Delegate>
{
MyView1 *_myView1;
}
...
@end
在AppDelegate.m中:
- (void)someCreateViewMethod
{
_myView1 = [[MyView1 alloc] initWithFrame:NSMakeRect(0, 0, 100, 200)];
[_myView1 setDelegate:self];
...
}
答案 2 :(得分:1)
我认为你应该使用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];
...
}