开发者

Delegation and Modal View Controllers

开发者 https://www.devze.com 2023-01-19 13:52 出处:网络
According to the View Controller Programming Guide, delegation is the preferred method to dismiss a modal view.

According to the View Controller Programming Guide, delegation is the preferred method to dismiss a modal view.

Following Apple's own Recipe example, i have implemented the following, but keep getting warnings that the addNameController:didAddName method is not found...

NameDelegate.h
    @protocol NameDelegate
    - (void)addNameController:(AddName *)addNameController didAddName:(NSString *)name;
    @end

AddName.h
    @interface AddName : UIViewController {
        UITextField *nameField;
        id delegate;
    }
    - (IBAction)doneAction;
    - (id)delegate;
    - (void)setDelegate:(id)newDelegate;
    @property (nonatomic, retain) IBOutlet UITextField *nameFiel开发者_如何学运维d;
    @end

AddName.m
    - (IBAction)doneAction {
        [delegate addNameController:self didAddName:[nameField text]];
    }

    - (id)delegate {
        return delegate;
    }

    - (void)setDelegate:(id)newDelegate {
        delegate = newDelegate;
    }

ItemViewController.h
    #import "NameDelegate.h"
    @interface ItemViewController : UITableViewController <NameDelegate>{
    }
    @end

ItemViewController.m
    - (void)addItem:(id)sender {

        AddName *addName = [[AddName alloc] init];
        addName.delegate = self;
        [self presentModalViewController:addName animated:YES];
    }

    - (void)addNameController:(AddName *)addNameController didAddName:(NSString *)name {
        //Do other checks before dismiss... 
        [self dismissModalViewControllerAnimated:YES];
    }

I think all the required elements are there and in the right place?

Thanks


You haven't specified that the delegate property of AddName has to conform to the NameDelegate protocol.

Use this code in AddName.h:

#import "NameDelegate.h"

@interface AddName : UIViewController {
    UITextField *nameField;
    id <NameDelegate> delegate;
}

@property(nonatomic, retain) IBOutlet UITextField *nameField;
@property(nonatomic, assign) id <NameDelegate> delegate;

- (IBAction)doneAction;

@end
0

精彩评论

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