上一篇簡單介紹了表視圖的一些基本概念,這一篇來做一個小小的Demo。
表視圖的加載順序是當(dāng)視圖控制器加載表視圖時訪問數(shù)據(jù)源方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
獲得單元格數(shù)量;然后訪問數(shù)據(jù)源方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
獲得每個單元格的數(shù)據(jù)。然后訪問初始化方法:
-initWithFrame:style:
初始化創(chuàng)建單元格。
下面這個Demo創(chuàng)建了一個表視圖,用來顯示一串?dāng)?shù)據(jù),數(shù)據(jù)中包含一個圖片和一段描述圖片的文字:
界面如下:

Paste_Image.png
這里創(chuàng)建的時候在表視圖屬性檢查器中有一個Content屬性,它可以選擇一個動態(tài)表和靜態(tài)表,這個屬性只有在故事板中才有。具體的在后面會介紹。同時在這個屬性后面有一個Prototype Cells,這個是原型單元格,給予id后可以在初始化單元格的時候調(diào)用,以用于重用。注意只能設(shè)置為一個,設(shè)置為兩個的話會出現(xiàn)錯誤。
代碼實現(xiàn)如下:
@interface ViewController () <UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSArray *listTeams; //單元格數(shù)據(jù)數(shù)組
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//將plist文件解析,獲得單元格數(shù)據(jù)數(shù)組
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"team.plist" ofType:nil];
self.listTeams = [[NSArray alloc]initWithContentsOfFile:filePath];
}
#pragma mark - tableViewDataSourse
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//返回單元格數(shù)量
return self.listTeams.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//為每個單元格添加數(shù)據(jù)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
//默認(rèn)情況下單元格主視圖樣式為在最左邊有一個ImageView,挨著有一個Label
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSDictionary *data = self.listTeams[indexPath.row];
cell.textLabel.text = data[@"name"];
cell.imageView.image = [UIImage imageNamed:data[@"image"]];
return cell;
}
@end