一:建立编辑联系人的controller,并使其拥有模型contact,且有协议。代码如下
#import <UIKit/UIKit.h>
#import "contact.h"
@class EditContactViewController ;
@protocol EditContactViewControllerDelegate<NSObject> - (void) editContactViewController:(EditContactViewController *)editContactViewController finishedSaveContact:(contact *)con; @end @interface EditContactViewController : UIViewController
@property (strong, nonatomic) contact *contact;
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *telField;
@property (weak, nonatomic) id <EditContactViewControllerDelegate> delegate; @end
.m文件中代码如下:
#import "EditContactViewController.h" @interface EditContactViewController ()
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *editBtn; @end @implementation EditContactViewController - (void)viewDidLoad {
[super viewDidLoad];
self.nameField.text = self.contact.name;
self.telField.text = self.contact.tel;
}
- (IBAction)saveBtnClick:(id)sender {
if ([self.delegate respondsToSelector:@selector(editContactViewController:finishedSaveContact:)])
{
// NSLog(@"%s",__func__);
self.contact.name = self.nameField.text;
self.contact.tel = self.telField.text;
[self.delegate editContactViewController:self finishedSaveContact:self.contact];
}
} - (IBAction)editBtnClick:(id)sender {
self.nameField.enabled = !self.nameField.enabled;
self.telField.enabled = !self.telField.enabled;
self.saveBtn.hidden = !self.saveBtn.hidden;
if (self.nameField.enabled) {
self.editBtn.title = @"取消";
}else {
self.editBtn.title = @"编辑";
}
} @end
二:
(1)在contactsController中将被点击的cell中的数据传给编辑人控制器,代码如下:
// 判断目标控制器类型
if ([destVc isKindOfClass:[EditContactViewController class]]) {
EditContactViewController *edit = destVc;
NSInteger indexPathOfRow = self.tableView.indexPathForSelectedRow.row;
// 获取要传递给目标控制器的contact
contact *con = self.contacts[indexPathOfRow];
// 设置目标控制器的contact属性
edit.contact = con;
// 设置自己为目标控制器的代理
edit.delegate = self;
}
(2)在contactsController中实现代理方法,并刷新数据,代码如下:
- (void)editContactViewController:(EditContactViewController *)editContactViewController finishedSaveContact:(contact *)con
{
// 获取联系人的数据 并加载到自己的联系人里
// 在自己的数组中找到当时传入的contact,并获取哪一行
NSInteger row = [self.contacts indexOfObject:con];
// 找到要刷新的那一个cell
NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:];
// 局部刷新
[self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:YES];
// 隐藏编辑联系人控制器
[self.navigationController popViewControllerAnimated:YES];
}
三:实际效果如下: