接續上一篇,這次要補完登出流程、輸入框連動,以及最關鍵的「資料逆傳」——也就是把新增頁面的資料送回列表頁面。
點擊登出按鈕後彈出對話框,確認則移除當前棧頂控制器回到開始畫面,取消則不做任何事。實作 actionSheet:clickedButtonAtIndex: 前,記得遵循 UIActionSheetDelegate 協議。
// 登出按鈕
- (IBAction)logoutBtn:(id)sender {
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"確定要登出?"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"確定"
otherButtonTitles:nil];
[sheet showInView:self.view];
}
#pragma mark - 代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != 0) return;
// 移除棧頂的控制器
[self.navigationController popViewControllerAnimated:YES];
}
這裡的 destructiveButtonIndex 為 0,也就是「確定」;「取消」的索引為 1。判斷條件寫成 != 0 就 return,是因為只有破壞性按鈕需要處理。
這裡用到通知機制。監聽 UITextField 的文字變動通知,收到後再決定按鈕是否可用。
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 取得通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 2. 註冊監聽
[center addObserver:self
selector:@selector(textChange)
name:UITextFieldTextDidChangeNotification
object:self.nameFeild];
[center addObserver:self
selector:@selector(textChange)
name:UITextFieldTextDidChangeNotification
object:self.phoneFeild];
}
// 文字改變時會呼叫此方法
- (void)textChange {
// 兩個輸入框都有值時,新增按鈕才變成可互動
self.addBtn.enabled = (self.nameFeild.text.length > 0 && self.phoneFeild.text.length > 0);
}
// 臨終遺言:務必移除觀察者,否則會 crash
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
dealloc 中的 removeObserver 不是可選動作。在舊版 runtime 中,未移除觀察者會在通知發送時存取已釋放的記憶體而崩潰。
YYContatcsViewController.m:
#import "YYContatcsViewController.h"
#import "YYAddViewController.h"
#import "YYInfoModel.h"
// 遵循協議
@interface YYContatcsViewController () <UIActionSheetDelegate, YYAddViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableview;
// 用來保存使用者新增的資料
@property (nonatomic, strong) NSMutableArray *array;
- (IBAction)logoutBtn:(id)sender;
@end
@implementation YYContatcsViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
// 登出按鈕
- (IBAction)logoutBtn:(id)sender {
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"確定要登出?"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"確定"
otherButtonTitles:nil];
[sheet showInView:self.view];
}
#pragma mark - 代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != 0) return;
[self.navigationController popViewControllerAnimated:YES];
}
// 在 segue 轉場前把 delegate 綁上
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UIViewController *c = segue.destinationViewController;
YYAddViewController *addc = (YYAddViewController *)c;
addc.delegate = self;
}
#pragma mark - YYAddViewControllerDelegate
- (void)addViewControllerDidAddBtn:(YYAddViewController *)addViewController
contatc:(YYInfoModel *)contatc {
NSLog(@"%@, %@", contatc.name, contatc.phone);
[self.array addObject:contatc];
[self.tableview reloadData];
}
// 懶載入
- (NSMutableArray *)array {
if (_array == nil) {
_array = [NSMutableArray array];
}
return _array;
}
#pragma mark - tableview 的資料源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"info";
// 先從緩存取;若無,則到 storyboard 中建立(需在 storyboard 把 cell 的識別符設為 info)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
YYInfoModel *info = self.array[indexPath.row];
cell.textLabel.text = info.name;
cell.detailTextLabel.text = info.phone;
return cell;
}
@end
YYAddViewController.h:
#import <UIKit/UIKit.h>
@class YYAddViewController, YYInfoModel;
// 自訂協議,讓上一個控制器成為當前控制器的委派對象
@protocol YYAddViewControllerDelegate <NSObject>
- (void)addViewControllerDidAddBtn:(YYAddViewController *)editViewController
contatc:(YYInfoModel *)contatc;
@end
@interface YYAddViewController : UIViewController
// 新增委派屬性
@property (nonatomic, strong) id <YYAddViewControllerDelegate> delegate;
@end
YYAddViewController.m:
#import "YYAddViewController.h"
#import "YYInfoModel.h"
@interface YYAddViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameFeild; // 姓名輸入框
@property (weak, nonatomic) IBOutlet UITextField *phoneFeild; // 電話號碼輸入框
@property (weak, nonatomic) IBOutlet UIButton *addBtn; // 新增按鈕
- (IBAction)addBtnOnclick:(id)sender;
@end
@implementation YYAddViewController
#pragma mark - 監聽是否可新增
- (void)viewDidLoad {
[super viewDidLoad];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(textChange)
name:UITextFieldTextDidChangeNotification
object:self.nameFeild];
[center addObserver:self
selector:@selector(textChange)
name:UITextFieldTextDidChangeNotification
object:self.phoneFeild];
}
- (void)textChange {
self.addBtn.enabled = (self.nameFeild.text.length > 0 && self.phoneFeild.text.length > 0);
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// 主動喚出鍵盤
[self.nameFeild becomeFirstResponder];
}
- (IBAction)addBtnOnclick:(id)sender {
// 1. 把當前畫面輸入框的資訊存進模型
YYInfoModel *info = [[YYInfoModel alloc] init];
info.name = self.nameFeild.text;
info.phone = self.phoneFeild.text;
// 2. 資料逆傳:透過委派把資料送回上一個控制器
// 先確認委派有實作該方法,避免 unrecognized selector
if ([self.delegate respondsToSelector:@selector(addViewControllerDidAddBtn:contatc:)]) {
[self.delegate addViewControllerDidAddBtn:self contatc:info];
}
// 3. 關閉自己,回到列表頁
[self.navigationController popViewControllerAnimated:YES];
}
@end
資料逆傳的三個要素是:定義協議、宣告 delegate 屬性、在合適的時機綁定委派。這裡用的是 storyboard segue,所以在 prepareForSegue:sender: 中綁定;若是以程式碼 push,則在 push 之前設定即可。
呼叫前用 respondsToSelector: 檢查是很值得保留的習慣。若協議方法標記為 @optional 而委派方未實作,直接呼叫就會崩潰。
最後,委派屬性應宣告為 assign 或 unsafe_unretained(MRC 時代)/weak(ARC 時代),避免父子控制器互相持有形成循環引用。範例中寫成 strong 在這個小 Demo 裡不會出問題,但正式專案請改用 weak。