這次要實作的是一個英雄展示頁:點擊任一列會彈出輸入框,讓使用者修改該英雄的名稱,完成後畫面立刻更新。

初始畫面:

點擊選取列後彈出修改框:

修改完成、資料自動刷新:

// YYheros.h #import <Foundation/Foundation.h> #import "Global.h" @interface YYheros : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *icon; @property (nonatomic, copy) NSString *intro; YYinitH(hero) // 用巨集展開 initWithDict: 與 herosWithDict: @end
// YYheros.m #import "YYheros.h" @implementation YYheros YYinitM(hero) @end
// YYViewController.m
#import "YYViewController.h"
#import "YYheros.h"
@interface YYViewController () <UITableViewDataSource, UIAlertViewDelegate, UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSArray *heros;
@end
@implementation YYViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableview.dataSource = self;
self.tableview.delegate = self;
self.tableview.rowHeight = 60.f;
}
#pragma mark - 懶載入
- (NSArray *)heros {
if (_heros == nil) {
NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];
NSArray *tempArray = [NSArray arrayWithContentsOfFile:fullPath];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in tempArray) {
[arrayM addObject:[YYheros herosWithDict:dict]];
}
_heros = [arrayM mutableCopy]; // 必須是可變陣列,後續要改模型
}
return _heros;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.heros.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"hero";
// 1. 先從重用池取
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 2. 取不到才建立
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
// 3. 帶入該列的模型
YYheros *hero = self.heros[indexPath.row];
cell.textLabel.text = hero.name;
cell.imageView.image = [UIImage imageNamed:hero.icon];
cell.detailTextLabel.text = hero.intro;
return cell;
}
#pragma mark - 刷新:第一步,彈出輸入框
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
YYheros *hero = self.heros[indexPath.row];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"修改資料"
message:nil
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"確定", nil];
// alert.alertViewStyle = UIAlertViewStyleSecureTextInput; // 密碼樣式
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *text = [alert textFieldAtIndex:0];
text.text = hero.name; // 把目前的值帶進輸入框,方便直接改
alert.tag = indexPath.row; // 用 tag 記住是哪一列
[alert show];
}
#pragma mark - 刷新:第二步,改模型再 reload
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (0 == buttonIndex) return; // 按取消,什麼都不做
// 1. 修改模型
YYheros *hero = self.heros[alertView.tag];
UITextField *text = [alertView textFieldAtIndex:0];
hero.name = text.text;
// 2. 刷新表格
// 全量刷新:會重新觸發 numberOfSections / numberOfRows / cellForRow
// [self.tableview reloadData];
// 局部刷新:只重載指定列,動畫與效能都更好
NSIndexPath *path = [NSIndexPath indexPathForRow:alertView.tag inSection:0];
[self.tableview reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationRight];
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
@end
如果完全不做刷新,畫面不會有任何變化——因為 cell 的內容只在 cellForRowAtIndexPath: 被呼叫時才會更新,得等到該 cell 因滾動被重複配置時才會顯示新值。這說明了刷新本質上就是「請 tableview 重新問一次資料源」。
「字典轉模型」這段程式碼每寫一個模型就要重打一次,可以封裝成帶參數的巨集放進 Global.h:
// Global.h
#ifndef _0____________Global_h
#define _0____________Global_h
// 宣告:展開為初始化方法與工廠方法
#define YYinitH(name) - (instancetype)initWithDict:(NSDictionary *)dict;\
+ (instancetype)herosWithDict:(NSDictionary *)dict;
// 實作:用 KVC 一次帶入所有同名屬性
#define YYinitM(name) - (instancetype)initWithDict:(NSDictionary *)dict {\
if (self = [super init]) {\
[self setValuesForKeysWithDictionary:dict];\
}\
return self;\
}\
+ (instancetype)herosWithDict:(NSDictionary *)dict {\
return [[self alloc] initWithDict:dict];\
}
#endif
之後在 YYheros.h 寫 YYinitH(hero)、在 .m 寫 YYinitM(hero),就能省下十幾行重複程式碼。使用巨集的前提是續行字元 \ 不能漏,且巨集內容最好保持單純——邏輯複雜的程式碼放進巨集,除錯時會很痛苦。
刷新的觀念濃縮成兩步:先改模型,再刷新表格(全部刷新或只刷指定列皆可,資料量大時優先用後者)。
另外注意控制器一共符合了三個協議:UITableViewDataSource 負責供資料、UITableViewDelegate 負責互動(didSelectRow)、UIAlertViewDelegate 負責接收輸入框的結果。這三者各司不同階段,混在一起看容易亂,分開理解就清楚了。
基本三步驟:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // 幾組 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; // 每組幾列 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; // 每列放什麼
組數與列數幾乎都與資料相關,資料通常存在 plist,需先轉成模型陣列。設定 cell 的動作則是:取出或建立(注意重用與快取)→ 帶入資料 → 回傳。
cell 的三種寫法:
UITableViewCell 樣式。用 xib 自訂 view 的七個步驟:建立 xib 描述外觀 → 建立自訂類別(父類別依 xib 的 root 而定)→ 類別名盡量與 xib 檔同名 → 完成連線 → 提供一個類別方法回傳已載入的 view(把 xib 載入細節藏起來)→ 對外開一個模型屬性 → 在模型 setter 中把資料填進子控件。
純程式碼自訂 cell 的六個步驟:建立繼承自 UITableViewCell 的子類別 → 覆寫 initWithStyle:reuseIdentifier: 建立並一次性設定子控件(記得加到 contentView 上)→ 準備資料模型與 frame 模型兩種模型 → cell 只持有 frame 模型,不直接持有資料模型 → 覆寫 frame 模型的 setter,在其中同時安排子控件的內容與位置 → frame 模型以懶載入建立,確保每個 cell 只算一次。
使用 delegate 的五個步驟:先確認誰是誰的代理 → 定義協議(命名慣例:類別名 + Delegate)→ 定義代理方法(多為 @optional,以控件名開頭,且至少帶一個參數把控件本身傳出去)→ 設定 delegate 物件並實作方法 → 在恰當時機呼叫代理方法(呼叫前先用 respondsToSelector: 確認對方有實作)。