TableView的用法
TableView是繼承ScrollView,在ScrollView還未出現之前,所有的滑動視圖都是用TableView來定製的,TableView是必須要實現它自身的兩個代理方法的,下面是TableView的一些基本屬性和方法的應用
要注意的是(對於所有的ScrollView及其子類來說):
第一次添加到控制器視圖上的子視圖如果是ScrollView的對象(包含ScrollView子類的對象),則視圖的內容偏移量會根據是否有導航欄和標籤欄進行擴充
表視圖創建時的基本樣式:
UITableViewStyleGrouped:分組樣式
UITableViewStylePlain: 平鋪樣式(默認)
設置tableView的內容偏移量
tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
tableView.backgroundColor = [UIColor redColor];
設置數據源
tableView.dataSource = self;
[self.view addSubview:tableView];
處理數據
獲取文件路徑--方法一
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"font" ofType:@"plist"];
拿到bundle的源路徑---方法二
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
//文件路徑
NSString *filePath = [resourcePath stringByAppendingPathComponent:@"font.plist"];
根據一個文件路徑返回一個數組
self.data = [NSArray arrayWithContentsOfFile:filePath];
}
必須實現的兩個代理方法
1-----返回多少行---每一組的行數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
先拿到小數組
NSArray *sectionData = self.data[section];
返回小數組的個數
return sectionData.count;
}
2----------返回的每一個單元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
取到小數組
NSArray *sectionArray = self.data[indexPath.section];
拿到小數組中對應的元素
NSString *fontName = [sectionArray objectAtIndex:indexPath.row];
cell.textLabel.text = fontName;
cell.textLabel.font = [UIFont fontWithName:fontName size:20];
return cell;
}
可選的代理方法
1-------返回每一組的頭視圖標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [NSString stringWithFormat:@"第%ld組Header", section];
}
2---------返回每一組的尾視圖標題
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return [NSString stringWithFormat:@"第%ld組Footer", section];
}