UITableView 是 iOS 列表界面的核心元件。同一個功能,可以用純程式碼、StoryBoard/XIB,或自訂元件三種方式建立。以下逐一示範。
關鍵是設定 dataSource,並實作 section 數量、每組標題、每組列數與 cell 內容這幾個方法。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
// style: UITableViewStyleGrouped —— 分組樣式
// style: UITableViewStylePlain —— 當組名稱滑動到頂部時會固定在頂部
UITableView *tabview = [[UITableView alloc] initWithFrame:self.view.frame
style:UITableViewStylePlain];
tabview.backgroundColor = [UIColor yellowColor];
tabview.dataSource = self;
[self.view addSubview:tabview];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [NSString stringWithFormat:@"分組%zd", section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc]
initWithFrame:CGRectMake(0, 0,
CGRectGetWidth(self.view.bounds), 50)];
cell.textLabel.text = [NSString stringWithFormat:@"hello%zd", indexPath.row];
return cell;
}建立 ViewController 時同時勾選建立 .xib 檔,把 UITableView 拖進去,再用 IBOutlet 連到程式碼即可。
#import "SecondViewController.h"
@interface SecondViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tabview;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 從它的 nib 載入完成後的額外設定
self.tabview.backgroundColor = [UIColor greenColor];
}
@end這種方式的好處是位置與樣式在 Storyboard 上看得見,坏处是佈局邏輯散落在檔案與程式碼兩邊。
如果同一個列表會在多處重複使用,把它包成一個獨立元件會更乾淨。做法是建立一個 .xib 檔,裡面只放一個 UITableView,然後寫一個類別方法負責從 xib 載入。
// CustomTabView.h #import <UIKit/UIKit.h> @interface CustomTabView : UITableView + (instancetype)tableViewWithDataSource:(id<UITableViewDataSource>)dataSource; @end
// CustomTabView.m
#import "CustomTabView.h"
@implementation CustomTabView
+ (instancetype)tableViewWithDataSource:(id<UITableViewDataSource>)dataSource {
CustomTabView *customTabView =
[[[NSBundle mainBundle] loadNibNamed:@"CustomTabView"
owner:self
options:nil] lastObject];
customTabView.dataSource = dataSource;
return customTabView;
}
@end使用端只要一行就能拿到配置好的列表:
// ThirdViewController.m
#import "ThirdViewController.h"
#import "CustomTabView.h"
@interface ThirdViewController () <UITableViewDataSource>
@end
@implementation ThirdViewController
- (void)viewDidLoad {
[super viewDidLoad];
CustomTabView *tabview = [CustomTabView tableViewWithDataSource:self];
[self.view addSubview:tabview];
}
@end三種方式該怎麼選? demo 或極簡單頁面用純程式碼最快;需要複雜靜態佈局時用 XIB;而只要同一個列表會重複出現,就值得抽成自訂元件,後續維護成本最低。