幾乎每個 App 都有設定頁,而設定頁的長相又高度相似:分組、箭頭、開關、勾選、badge。與其每個頁面重寫一次,不如抽出一套基類,之後只要描述資料,畫面自動生成。
1. 觀察原型圖。先看設計稿有哪些型態的 cell。
2. 找出共同點,抽成基類。目標是寫好一個基礎控制器後,其他設定頁只要填資料就能完成。
3. 決定用純程式碼還是 Storyboard。若各頁的控件位置固定不變,Storyboard 更省事;若 cell 結構需要動態變化,程式碼反而靈活。
至於要不要用靜態 cell(Static Cells):如果頁面 cell 與系統預設樣式幾乎一致,可以用;若彼此差異不大也可勉強用;差異很大時,果断改用程式碼。
// BasicTableViewController.h
// groups:每一組代表一個 section
@property (nonatomic, strong) NSMutableArray *groups;
// BasicTableViewController.m
#import "BasicTableViewController.h"
#import "GroupItem.h"
#import "SettingItem.h"
#import "BasicCell.h"
@implementation BasicTableViewController
// 讓這個類一初始化就是分組樣式
- (instancetype)init {
return [self initWithStyle:UITableViewStyleGrouped];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.backgroundColor = [UIColor colorWithRed:211 green:211 blue:211 alpha:1];
self.tableView.sectionHeaderHeight = 10;
self.tableView.sectionFooterHeight = 0;
self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
// 一定要懶加載,否則子類無法初始化它
- (NSMutableArray *)groups {
if (!_groups) {
_groups = [NSMutableArray array];
}
return _groups;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
GroupItem *group = self.groups[section];
return group.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BasicCell *cell = [BasicCell cellWithTableView:tableView];
GroupItem *group = self.groups[indexPath.section];
SettingItem *item = group.items[indexPath.row];
cell.item = item;
[cell setIndexPath:indexPath rowCount:group.items.count];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
return self.groups[section].footTitle;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.groups[section].headTitle;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
GroupItem *group = self.groups[indexPath.section];
SettingItem *item = group.items[indexPath.row];
if (item.destVc) { // 有指定目標控制器就跳轉
UIViewController *destVc = [[item.destVc alloc] init];
[self.navigationController pushViewController:destVc animated:YES];
}
if (item.option) { // 每個 cell 處理自己的行為
item.option();
}
}
@end
GroupItem 代表一組:
@interface GroupItem : NSObject
@property (nonatomic, strong) NSArray *items; // 這一組的行
@property (nonatomic, copy) NSString *headTitle;
@property (nonatomic, copy) NSString *footTitle;
@end
SettingItem 代表一行:
typedef void (^SettingItemOption)();
@interface SettingItem : NSObject
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subTitle;
@property (nonatomic, assign) Class destVc; // 跳轉目標,用 Class 而非字串
@property (nonatomic, copy) SettingItemOption option; // 點擊後的行為
+ (instancetype)itemWithTitle:(NSString *)title;
+ (instancetype)itemWithTitle:(NSString *)title image:(UIImage *)image;
@end
因為畫面完全由模型驅動,接著針對不同樣式再往下細分:
@interface ArrowItem : SettingItem // 箭頭樣式
@end
@interface BadgeItem : SettingItem // 數字標記
@property (nonatomic, copy) NSString *badgeValue;
@end
@interface SwitchItem : SettingItem // 開關
@property (nonatomic, assign) BOOL isOn;
@end
@interface LabelItem : SettingItem // 純文字(例如「登出」)
@property (nonatomic, copy) NSString *text;
@end
@interface CheakItem : SettingItem // 勾選
@property (nonatomic, assign) BOOL isCheak;
@end
@class SettingItem;
@interface BasicCell : UITableViewCell
@property (nonatomic, strong) SettingItem *item;
+ (instancetype)cellWithTableView:(UITableView *)tableView;
- (void)setIndexPath:(NSIndexPath *)indexPath rowCount:(NSInteger)rowCount;
@end
@interface BasicCell ()
// 這裡要用 strong:這些 view 是直接加在 cell 上,而不是加在 contentView
@property (nonatomic, strong) UIImageView *arrowView;
@property (nonatomic, strong) UISwitch *switchView;
@property (nonatomic, strong) UIImageView *cheakView;
@property (nonatomic, weak) UILabel *labelView;
@end
// 不易變形的可拉伸圖片(實務上建議獨立成 category)
@implementation UIImage (Resizable)
+ (UIImage *)resizableWithImageName:(NSString *)imageName {
UIImage *image = [UIImage imageNamed:imageName];
return [image stretchableImageWithLeftCapWidth:image.size.width/2
topCapHeight:image.size.height/2];
}
@end
@implementation BasicCell
#pragma mark - 所有子視圖懶加載
- (UIImageView *)arrowView {
if (_arrowView == nil) {
_arrowView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_icon_arrow"]];
}
return _arrowView;
}
- (UISwitch *)switchView {
if (_switchView == nil) {
_switchView = [[UISwitch alloc] init];
[_switchView addTarget:self action:@selector(switchChange:)
forControlEvents:UIControlEventValueChanged];
}
return _switchView;
}
- (UIImageView *)cheakView {
if (_cheakView == nil) {
_cheakView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_icon_checkmark"]];
}
return _cheakView;
}
- (UILabel *)labelView {
if (!_labelView) {
UILabel *labelView = [[UILabel alloc] initWithFrame:self.bounds];
labelView.textAlignment = NSTextAlignmentCenter;
labelView.textColor = [UIColor redColor];
[self.contentView addSubview:labelView];
_labelView = labelView;
}
return _labelView;
}
#pragma mark - 事件
- (void)switchChange:(UISwitch *)switchView {
}
// 只需設定一次的內容放在這裡,因為 init 只會在建立 cell 時呼叫一次
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.detailTextLabel.font = [UIFont systemFontOfSize:14];
self.backgroundColor = [UIColor clearColor];
self.backgroundView = [[UIImageView alloc] init];
self.selectedBackgroundView = [[UIImageView alloc] init];
}
return self;
}
// 注意這裡必須用 self 而不是 [BasicCell alloc]
+ (instancetype)cellWithTableView:(UITableView *)tableView {
static NSString *ID = @"cell";
BasicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[self alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
}
return cell;
}
#pragma mark - 模型驅動
- (void)setItem:(SettingItem *)item {
_item = item;
[self setUpData];
[self setUpRightView];
}
- (void)setUpData {
self.textLabel.text = _item.title;
self.detailTextLabel.text = _item.subTitle;
self.imageView.image = _item.image;
}
- (void)setUpRightView {
if ([_item isKindOfClass:[ArrowItem class]]) {
self.accessoryView = self.arrowView;
} else if ([_item isKindOfClass:[BadgeItem class]]) {
self.accessoryView = self.badgeView;
} else if ([_item isKindOfClass:[SwitchItem class]]) {
self.accessoryView = self.switchView;
} else if ([_item isKindOfClass:[LabelItem class]]) {
LabelItem *labelItem = (LabelItem *)_item;
self.labelView.text = labelItem.text;
} else if ([_item isKindOfClass:[CheakItem class]]) {
CheakItem *cheakItem = (CheakItem *)_item;
self.accessoryView = cheakItem.isCheak ? self.cheakView : nil;
} else {
[_labelView removeFromSuperview];
_labelView = nil;
self.accessoryView = nil;
}
}
// 依位置決定圓角背景圖
- (void)setIndexPath:(NSIndexPath *)indexPath rowCount:(NSInteger)rowCount {
UIImageView *bgView = (UIImageView *)self.backgroundView;
UIImageView *selBgView = (UIImageView *)self.selectedBackgroundView;
if (rowCount == 1) {
bgView.image = [UIImage resizableWithImageName:@"common_card_background"];
selBgView.image = [UIImage resizableWithImageName:@"common_card_background_highlighted"];
} else if (indexPath.row == 0) {
bgView.image = [UIImage resizableWithImageName:@"common_card_top_background"];
selBgView.image = [UIImage resizableWithImageName:@"common_card_top_background_highlighted"];
} else if (indexPath.row == rowCount - 1) {
bgView.image = [UIImage resizableWithImageName:@"common_card_bottom_background"];
selBgView.image = [UIImage resizableWithImageName:@"common_card_bottom_background_highlighted"];
} else {
bgView.image = [UIImage resizableWithImageName:@"common_card_middle_background"];
selBgView.image = [UIImage resizableWithImageName:@"common_card_middle_background_highlighted"];
}
}
// 只有寫在這裡才能正確置中對齊
- (void)layoutSubviews {
[super layoutSubviews];
_labelView.frame = self.bounds;
}
@end
「我的」頁面——示範如何組出多組資料:
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpNav];
[self setUpGroup0];
[self setUpGroup1];
[self setUpGroup2];
[self setUpGroup3];
}
- (void)setUpNav {
UIBarButtonItem *setting = [[UIBarButtonItem alloc] initWithTitle:@"設置"
style:UIBarButtonItemStylePlain
target:self
action:@selector(setting)];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSForegroundColorAttributeName] = [UIColor blackColor];
[setting setTitleTextAttributes:dict forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = setting;
}
- (void)setting {
SettingViewController *setVc = [[SettingViewController alloc] init];
[self.navigationController pushViewController:setVc animated:YES];
}
- (void)setUpGroup0 {
ArrowItem *friend = [ArrowItem itemWithTitle:@"新的好友" image:[UIImage imageNamed:@"new_friend"]];
GroupItem *group = [[GroupItem alloc] init];
group.items = @[friend];
[self.groups addObject:group];
}
- (void)setUpGroup1 {
ArrowItem *album = [ArrowItem itemWithTitle:@"我的相冊" image:[UIImage imageNamed:@"album"]];
album.subTitle = @"(12)";
ArrowItem *collect = [ArrowItem itemWithTitle:@"我的收藏" image:[UIImage imageNamed:@"collect"]];
collect.subTitle = @"(0)";
ArrowItem *like = [ArrowItem itemWithTitle:@"贊" image:[UIImage imageNamed:@"like"]];
like.subTitle = @"(0)";
GroupItem *group = [[GroupItem alloc] init];
group.items = @[album, collect, like];
[self.groups addObject:group];
}
設定頁——示範跳轉與客製 cell:
- (void)setUpGroup1 {
ArrowItem *notice = [ArrowItem itemWithTitle:@"提醒和通知"];
ArrowItem *setting = [ArrowItem itemWithTitle:@"通用設置"];
setting.destVc = [CommonViewController class]; // 指定跳轉目標
ArrowItem *secure = [ArrowItem itemWithTitle:@"隱私與安全"];
GroupItem *group = [[GroupItem alloc] init];
group.items = @[notice, setting, secure];
[self.groups addObject:group];
}
如果某頁的 cell 樣式與基類不同(例如「我的」頁的副標題要緊貼在標題右側),只要繼承 BasicCell 並覆寫即可:
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.detailTextLabel.font = [UIFont systemFontOfSize:12];
}
return self;
}
// 必須在 layoutSubviews 中覆寫:此時 frame 已 100% 正確
- (void)layoutSubviews {
[super layoutSubviews];
CGRect frame = self.detailTextLabel.frame;
frame.origin.x = CGRectGetMaxX(self.textLabel.frame) + 5;
self.detailTextLabel.frame = frame;
}
字型大小頁——示範用 block 處理點擊,並用 weakSelf 避免循環引用:
- (void)setUpGroup0 {
// 用 __weak 消除 block 對 self 的循環引用警告
__weak typeof(self) weakSelf = self;
CheakItem *big = [CheakItem itemWithTitle:@"大"];
big.option = ^{ [weakSelf selItem:big]; };
CheakItem *middle = [CheakItem itemWithTitle:@"中"];
middle.option = ^{ [weakSelf selItem:middle]; };
CheakItem *small = [CheakItem itemWithTitle:@"小"];
small.option = ^{ [weakSelf selItem:small]; };
GroupItem *group = [[GroupItem alloc] init];
group.headTitle = @"字體大小";
group.items = @[big, middle, small];
[self.groups addObject:group];
[self setUpSelItem:middle];
}
- (void)selItem:(CheakItem *)item {
_selCheakItem.isCheak = NO;
item.isCheak = YES;
_selCheakItem = item;
[self.tableView reloadData];
// 持久化
[[NSUserDefaults standardUserDefaults] setObject:item.title forKey:FontSizeKey];
[[NSUserDefaults standardUserDefaults] synchronize];
// 發出通知,讓其他頁面同步更新
[[NSNotificationCenter defaultCenter] postNotificationName:@"FontSizeChangeNote"
object:nil
userInfo:@{FontSizeKey: item.title}];
}
基類負責「怎麼畫」,子類只負責「畫什麼」。新增一個設定頁時,你要寫的只有幾個 setUpGroupN 方法,表格的 section 數、行數、cell 樣式、圓角背景、點擊行為全部自動到位。
遇到子類與父類長得很像但略有差異的情況,就利用 Objective-C 的繼承特性覆寫對應方法——例如覆寫 cellForRowAtIndexPath 換成自己的 cell 類,或覆寫 layoutSubviews 微調位置。這正是把「設定頁」抽象成模板方法模式的實際收益。