Step1:新建一个文件,命名为"LKAddViewController"
第2步:在LKAddViewController.h
定义UITextField
和UIButton
和delegate
方法类似..
#import <UIKit/UIKit.h>
#import "LKBook.h"
@protocol LKAddViewControllerDelegate;
@interface LKAddViewController : UIViewController
@property (nonatomic,strong)IBOutlet UITextField *txtField;
@property (nonatomic) id <LKAddViewControllerDelegate> AddBookDelegate;
@property (strong, nonatomic) IBOutlet UITextField *author;
@property (strong, nonatomic) IBOutlet UITextField *titletxt;
@property (nonatomic,strong)IBOutlet UIButton *submit;
-(IBAction)btnSubmit:(id)sender;
@end
@protocol LKAddViewControllerDelegate <NSObject>
- (void)AddBook:(LKBook *)newObj;
@end
Step3:在LKAddViewController.m
编写提交按钮的代码并调用委托方法,如..
@implementation LKAddViewController
@synthesize AddBookDelegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)btnSubmit:(id)sender{
LKBook *newBook = [[LKBook alloc] init];
newBook.author = self.author.text;
newBook.title = self.titletxt.text;
newBook.desc = self.titletxt.text;
if ([self.AddBookDelegate respondsToSelector:@selector(AddBook:)]) {
[self.AddBookDelegate AddBook:newBook];
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
步骤:4 在LKMasterViewController.h
导入头文件并定义委托方法,如..
#import "LKAddViewController.h"
@interface LKMasterViewController () <LKAddViewControllerDelegate>{
Step5:insertNewObject
用下面的代码替换你的方法
- (void)insertNewObject:(id)sender
{
LKAddViewController *obj = [[LKAddViewController alloc]initWithNibName:@"LKAddViewController" bundle:nil];
obj.AddBookDelegate=self;
[self.navigationController pushViewController:obj animated:YES];
// if (!_objects) {
// _objects = [[NSMutableArray alloc] init];
// }
// [_objects insertObject:[NSDate date] atIndex:0];
// NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
// [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
step6:编写以下方法来添加新对象并重新加载表。
- (void)AddBook:(LKBook *)newObj{
[myBookStore.BookStore addObject:newObj];
[self.tableView reloadData];
}
希望这对您有用并满足您的要求。