?UITableView?*DataTable;
? ??NSMutableArray?*dataArray1;?//定義數據數組1
? ??NSMutableArray?*dataArray2;//定義數據數組2
? ??NSMutableArray?*titleArray;//定義標題數組
}
- (void)viewDidLoad
{
? ? [superviewDidLoad];
//初始化tableview
? ??DataTable?= [[UITableViewalloc]?initWithFrame:CGRectMake(0,?0,?320,?420)];//指定位置大小
? ? [DataTablesetDelegate:self];//指定委托
? ? [DataTablesetDataSource:self];//指定數據委托
? ? [self.viewaddSubview:DataTable];//加載tableview
? ??dataArray1?= [[NSMutableArrayalloc]?initWithObjects:@"中國",?@"美國",?@"英國",?nil];//初始化數據數組1
? ??dataArray2?= [[NSMutableArrayalloc]?initWithObjects:@"黃種人",?@"黑種人",?@"白種人",?nil];//初始化數據數組2
? ??titleArray?= [[NSMutableArrayalloc]?initWithObjects:@"國家",?@"種族",?nil];//初始化標題數組
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
? ??// Return YES for supported orientations
? ??return?(interfaceOrientation ==?UIInterfaceOrientationPortrait);
}
//每個section顯示的標題
- (NSString?*)tableView:(UITableView?*)tableView titleForHeaderInSection:(NSInteger)section{
? ??switch?(section) {
? ? ? ??case?0:
? ? ? ? ? ??return?[titleArray?objectAtIndex:section];//提取標題數組的元素用來顯示標題
? ? ??? case 1:
? ? ? ? ? ??return?[titleArray?objectAtIndex:section];//提取標題數組的元素用來顯示標題
? ? ? ??default:
? ? ? ? ? ??return?@"Unknown";
? ? }
}
//指定有多少個分區(Section),默認為1
- (NSInteger)numberOfSectionsInTableView:(UITableView?*)tableView {
? ??return?[titleArray count];//返回標題數組中元素的個數來確定分區的個數
}
//指定每個分區中有多少行,默認為1
- (NSInteger)tableView:(UITableView?*)tableView numberOfRowsInSection:(NSInteger)section{
? ??switch?(section) {
? ? ? ??case?0:
?? ? ? ? ??return? [dataArray1?count];//每個分區通常對應不同的數組,返回其元素個數來確定分區的行數
? ? ? ? ? ??break;
? ? ? ??case?1:
? ? ? ? ? ??return? [dataArray2?count];
? ? ? ? ? ??break;
? ? ? ??default:
? ? ? ? ? ??return?0;
? ? ? ? ? ??break;
? ? }
}
//繪制Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
? ??static?NSString?*CellIdentifier =?@"Cell";
?//初始化cell并指定其類型,也可自定義cell
UITableViewCell?*cell = (UITableViewCell*)[tableView??dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell ==?nil)?
{
cell = [[[UITableViewCellalloc]?
initWithFrame:CGRectZero?
reuseIdentifier:CellIdentifier]?autorelease];
}
? switch?(indexPath.section) {
case 0://對應各自的分區
[[cell?textLabel] ?setText:[dataArray1 objectAtIndex:indexPath.row]];//給cell添加數據
break;
case 1:
[[cell?textLabel] ?setText:[dataArray2 objectAtIndex:indexPath.row]];
break;
default:
[[cell?textLabel] ?setText:@"Unknown"];
}
return?cell;//返回cell
}
tableview還有很多高難度的屬性和接口,在以后我會慢慢補齊。