使用 UITableView 時,常會遇到列表沒有資料的情況。此時若能顯示一張提示圖與一行說明文字,可以讓介面更友善,也能引導使用者下一步操作。
可以建立一個自訂 UITableView 子類,將提示圖片與文字封裝在內部。外部只要設定是否顯示提示、提示文字與圖片名稱即可。
@interface WFEmptyTableView : UITableView
@property (nonatomic, assign) BOOL showEmptyTipView;
@property (nonatomic, assign) NSInteger vOffset;
@property (nonatomic, copy) NSString *tipString;
@property (nonatomic, copy) NSString *tipImageName;
@end
在實作中,可建立一個背景視圖,放入 UIImageView 與 UILabel。當 showEmptyTipView 設為 YES 時,將背景視圖加入列表;設為 NO 時則移除。
- (void)setShowEmptyTipView:(BOOL)showEmptyTipView {
_showEmptyTipView = showEmptyTipView;
if (showEmptyTipView) {
[self addSubview:_customBackView];
} else {
[_customBackView removeFromSuperview];
}
}
- (void)setTipString:(NSString *)tipString {
_tipString = tipString;
_label.text = tipString;
[self resetFrame];
}
- (void)setTipImageName:(NSString *)tipImageName {
_tipImageName = tipImageName;
UIImage *image = [UIImage imageNamed:tipImageName];
_tipImageView.image = image;
[self resetFrame];
}
若不希望建立新的子類,也可以透過 Category 為 UITableView 增加提示視圖能力。概念是使用關聯物件,將提示視圖附加到 table view 上,再由外部呼叫方法顯示。
@interface UITableView (WFEmpty)
- (void)addEmptyViewWithImageName:(NSString *)imageName title:(NSString *)title;
@end
實作時,可建立一個包含 UIImageView 與 UILabel 的 UIView,將其加入 UITableView,並透過關聯物件保存參考。這樣就能在不修改原有類別繼承結構的情況下,快速加入空資料提示。
若專案需要大量重複使用,且希望提示樣式一致,繼承 UITableView 會較清楚;若希望以較低侵入性的方式加入功能,Category 會更靈活。