標籤:
一:建立編輯連絡人的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:0];// 局部重新整理 [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:YES];// 隱藏編輯連絡人控制器 [self.navigationController popViewControllerAnimated:YES];}
三:實際效果如下:
2016-1-5第一個完整APP 私人通訊錄的實現 4:編輯連絡人