標籤:des style blog http io os ar 使用 for
建立一個tableView,直接拖拽放在storyboard裡面即可。
(1)先建立一個資料模型類WSCarGroup,在WSCarGroup.h檔案中:
#import <Foundation/Foundation.h>@interface WSCarGroup : NSObject@property(nonatomic,copy) NSString * title;@property(nonatomic,copy) NSString * desc;@property(nonatomic,strong) NSArray *cars;@end
(2)在ViewController.m中:
——先把資料轉成模型,這裡沒有plist,所以直接手動輸入。
先聲明一個裝模型的陣列變數
@property (nonatomic,strong) NSArray *carGroups;
-(NSArray *)carGroups{ if (_carGroups==nil) { WSCarGroup *cg1=[[WSCarGroup alloc]init]; [email protected]"德系汽車"; [email protected]"品質最精良"; [email protected][@"寶馬",@"奧迪",@"平治"]; WSCarGroup *cg2=[[WSCarGroup alloc]init]; [email protected]"日系汽車"; [email protected]"很輕很省油"; [email protected][@"三菱",@"日產",@"本田",@"三菱",@"日產",@"本田",@"三菱",@"日產",@"本田",@"三菱",@"日產",@"本田"]; [email protected][cg1,cg2]; } return _carGroups;}
——設定tableView的資料來源,和協議類似,充當資料來源的要遵守“協議”。此處我們把ViewController當做資料來源。所以先遵守:
@interface ViewController ()<UITableViewDataSource>
——然後設定成資料來源
- (void)viewDidLoad { self.tableView.dataSource=self; [super viewDidLoad];}
——tableView最重要的幾個方法
111、設定多少組(如果省略這個方法,則預設是1組)
222、設定每組有多少行
333、設定每行的cell填充什麼內容(最重要)
444、設定每組頭部標題文字
555、設定妹婿尾部標題文字
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return self.carGroups.count;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ WSCarGroup *cg=self.carGroups[section]; return cg.cars.count;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //因為要返回UITableViewCell,所以先建立一個,然後賦值,最後返回,即可。 UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; WSCarGroup *cg=self.carGroups[indexPath.section]; cell.textLabel.text=cg.cars[indexPath.row]; return cell;}-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ WSCarGroup *cg=self.carGroups[section]; return cg.title;}-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ WSCarGroup *cg=self.carGroups[section]; return cg.desc;}
——當然,為了展示方便,隱藏頂部狀態列
-(BOOL)prefersStatusBarHidden{ return YES;}
tableView有兩種展現形式:plain和grouped。
——plain就是每組之間間隔很小,分組不明顯。grouped每組間隔大分組明顯。如下:
——plain有頭部懸停效果,類似於QQ分組好友的那個組名稱在最頂部懸停,直到被下一組頂替。
【iOS開發-58】tableView初識:5個重要方法的使用和2種樣式的區別