本文示範如何透過 Xib 來設計並使用自訂的 UITableViewCell,打造版面一致的列表畫面。這類做法特別適合團購列表、新聞列表等「每個單元格格式相同」的應用場景。
主控制器負責實作 TableView 的 delegate 與 dataSource,載入並解析資料,同時設定列表的頭部與尾部視圖:
- (void)viewDidLoad {
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:@"SLFooterView" bundle:nil];
SLFooterView *footerview = [[nib instantiateWithOwner:nil options:nil] firstObject];
self.tableview.tableFooterView = footerview;
footerview.delegate = self;
SLHeaderView *headerview = [SLHeaderView headerWithView];
self.tableview.tableHeaderView = headerview;
}
// 解析 plist 資料檔
-(NSMutableArray *)arrayM {
if (_arrayM == nil) {
NSString *fullpath = [[NSBundle mainBundle] pathForResource:@"tgs" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:fullpath];
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary *dict in array) {
SLTgDatas *data = [SLTgDatas tgDataWithDiectionary:dict];
[arr addObject:data];
}
_arrayM = arr;
}
return _arrayM;
}
// 填充資料並顯示
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SLTableViewCell *cell = [SLTableViewCell cellWithTabelViewCell:tableView];
SLTgDatas *data = self.arrayM[indexPath.row];
cell.data = data;
return cell;
}
這個類別負責將 plist 中的字典轉為物件模型,並延遲載入圖片:
-(UIImage *)image {
if (_image == nil) {
_image = [UIImage imageNamed:self.icon];
}
return _image;
}
-(instancetype)initWithTgDirectionary:(NSDictionary *)dict {
if (self = [self init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype)tgDataWithDiectionary:(NSDictionary *)dict {
return [[self alloc] initWithTgDirectionary:dict];
}
自訂 Cell 透過 Xib 設計並以連線關聯各元件,方便控制器調用。關鍵在於提供一個以 Xib 載入 Cell 的便利方法:
+(instancetype)cellWithTabelViewCell:(UITableView *)table {
static NSString *str = @"cell";
SLTableViewCell *cell = [table dequeueReusableCellWithIdentifier:str];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"SLTgPlistView" owner:nil options:nil] firstObject];
}
return cell;
}
-(void)setData:(SLTgDatas *)data {
_data = data;
self.cellbuycount.text = data.buyCount;
self.cellImage.image = data.image;
self.cellprice.text = data.price;
self.celltitle.text = data.title;
}
透過自訂的 footer view 搭配 delegate,實作點擊載入更多資料的效果:
- (IBAction)btnclick {
self.clieckbt.hidden = YES;
self.jiazai.hidden = NO;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if ([self.delegate respondsToSelector:@selector(loadMoreData)]) {
[self.delegate loadMoreData];
}
self.clieckbt.hidden = NO;
self.jiazai.hidden = YES;
});
}
自訂 UITableViewCell 主要有兩種方式:純程式碼與 Xib。使用 Xib 能讓版面設計更直觀、便於調整,適合格式固定且重複性高的列表。實際開發時,可依據不同場景靈活選用合適的做法。