上一篇簡單介紹了表視圖的一些基本概念,這一篇來做一個小小的Demo。
表視圖的加載順序是當視圖控制器加載表視圖時訪問數據源方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
獲得單元格數量;然后訪問數據源方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
獲得每個單元格的數據。然后訪問初始化方法:
-initWithFrame:style:
初始化創建單元格。
下面這個Demo創建了一個表視圖,用來顯示一串數據,數據中包含一個圖片和一段描述圖片的文字:
界面如下:
Paste_Image.png
這里創建的時候在表視圖屬性檢查器中有一個Content屬性,它可以選擇一個動態表和靜態表,這個屬性只有在故事板中才有。具體的在后面會介紹。同時在這個屬性后面有一個Prototype Cells,這個是原型單元格,給予id后可以在初始化單元格的時候調用,以用于重用。注意只能設置為一個,設置為兩個的話會出現錯誤。
代碼實現如下:
@interface ViewController () <UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSArray *listTeams; //單元格數據數組
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//將plist文件解析,獲得單元格數據數組
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 {
//返回單元格數量
return self.listTeams.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//為每個單元格添加數據
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
//默認情況下單元格主視圖樣式為在最左邊有一個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