標籤:
UITableView常用來展示資料,類似於Android中的ListView,相對於Android中的ListView而言,UITableView的實現是非常簡單,繼承UITableViewDataSource,
UITableViewDelegate然後根據需要是實現對應的方法即可。 UITableView有兩個預設的內建風格,Plain和Grouped,Plain表明表格視圖自身沒有真正地在你自己實際地提供任何外觀之前提供很多的外觀,大部分情況下,它會做的唯一的事情是它會給你這些header和footer。Grouped表格視圖是UIKit提供的分組風格。風格的話如果有特別的需求,還可以自訂分組的風格。
頁面配置
頁面比較簡單,一個簡單UITableView:
標頭檔中的不需要聲明,需要實現一下協議:
@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>@end
Demo實現
聲明三個資料用來展示資料:
@interface ViewController (){ NSArray *channelArr; NSMutableArray *filmArr; NSMutableArray *tvArr;}@end
初始化資料:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. channelArr=[[NSArray alloc] initWithObjects:@"電影",@"電視劇",nil]; filmArr=[[NSMutableArray alloc] initWithObjects:@"智取威虎山",@"一步之遙",@"匆匆那年",@"北京愛情故事",nil]; tvArr=[[NSMutableArray alloc] initWithObjects:@"何以笙簫默",@"鋒刃",@"陸小鳳與花滿樓",@"武媚娘傳奇",nil];}
設定分組的組數:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ NSLog(@"%lu",(unsigned long)channelArr.count); return [channelArr count];}
設定分組的標題:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ return [channelArr objectAtIndex:section];}
設定每個分組下內容的個數:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSInteger count=0; switch (section) { case 0: count=[filmArr count]; break; case 1: count=[tvArr count]; break; } return count;}
設定每個分組下的具體內容:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; switch (indexPath.section) { case 0: [cell.textLabel setText:[filmArr objectAtIndex:indexPath.row]]; break; case 1: [cell.textLabel setText:[tvArr objectAtIndex:indexPath.row]]; break; } return cell;}
設定分組標題和底部的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ return 40;}- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{ return 0;}
設定點擊事件:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSString *content; switch (indexPath.section) { case 0: content=[NSString stringWithFormat:@"%@-%@",channelArr[0],[filmArr objectAtIndex:indexPath.row]]; break; case 1: content=[NSString stringWithFormat:@"%@-%@",channelArr[1],[tvArr objectAtIndex:indexPath.row]]; break; } UIAlertView *alterView=[[UIAlertView alloc] initWithTitle:@"當前位置:" message:content delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alterView show];}
最終效果:
iOS開發-UITableView常用方法