开发者

Making a delegate for a UIViewController

I've looked all over, and found many people with similar problems, but I still can't get my delegates working. I want to make a model view controller pop up, then call a method in the view that made the model view asking it to dismiss it. So I have this line:

mergeConfig *view = [[mergeConfig alloc] initWithNibName:@"mergeConfig" bundle:nil];

and I'm trying [view setDelegate:self]; as said to on apple's developer page开发者_运维技巧s, but expectably my model view doesn't have a setDelegate method.

So what I want to know is, how do I get it so that I can set a delegate? And then once I do, does it just automatically pass calls to methods to methods in the parent view with the same name? Apple's pages didn't say what code to put in the model view controller.


You need to define a delegate on your custom view controller, as such:

@interface mergeConfig {
    id delegate;
}
@property (nonatomic, assign) id delegate;        
@end

@implementation mergeConfig
@synthesize delegate;
@end

Then, elsewhere in the class for your view controller you can invoke whatever methods you need on your delegate.

Personally I like to improve the above by defining a protocol that my delegates comply to, as follows:

@protocol MyDelegateProtocol
- (void)delegateMethod;
@end

@interface mergeConfig {
    id<MyDelegateProtocol> delegate;
}
@property (nonatomic, assign) id<MyDelegateProtocol> delegate;        
@end

@implementation mergeConfig
@synthesize delegate;
@end


If you simply need to dismiss the modal view controller, just call [self.parentViewController dismissModalViewControllerAnimated:YES]; at the appropriate time. No need for delegates unless you need to pass information back up the chain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜