本節學習內容:
1.UITableView基本概念
2.UITableView基本創建
3.UITableView的基本使用
【UITableView屬性】
dataSource:數據代理對象
delegate:普通代理對象
numberOfSectionsInTableView:獲取組數協議
numberOfRowsInSection:獲取行數協議
cellForRowAtIndexPath:創建單元格協議
【ViewController.h】
#import<UIKit/UIKit.h>
@interface
//UITableViewDelegate:實現數據視圖的普通協義,數據視圖的普通事件處理
//UITableViewDataSource 實現數據視圖的數據代理協議,處理數據視圖的數據代理
viewController:UIViewController<UITableViewDelegate,UITableViewDataSource>
{
//定義一個數據視圖對象,數據視圖用來顯示大量相同格式的信息的視圖,例如:電話通記錄,朋友圈信息...
UITableView* _tableView;
}
@end
【ViewController.m】
-(void)viewDidLoad{
[super viewDidLoad];
//創建數據視圖,參數1:數據視圖的位置,參數2:數據視圖的峁格,UITableViewStylePlain表示普通風,UITableViewStyleGruped表示分組風格
_tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
//設置數據視圖的代理對象
_tableView.delegate=self;
//設置數據視圖的數據源對象
_tableView.dataSource=self;
【self.view addSubview:_tableView】
}
//獲取每組元素的個數(行數),必須要實現的協義函數,程序在顯示數據視圖時會調用此函數,返回值:表示每組元素的個數,參數1:數據視圖對象本身,參數2:那一組需要的行數
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5;
}
//設置數據視圖的組數
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
//創建單元格對象函數
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
NSString* cellStr=@"cell";
UITableViewCell* cell=[_tableView dequeueReusableCellWithIdentifier:cellStr];
if(cell ==nil){
//創建一個單元格對象,參數一:單元格的樣式,參數二:單元格的復用標記
cell=[[UITableViewCell alloc]iniWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
}
NSString* str=[NSSTring stringWithFormat:@"每%組,第%d行",indexPath.section,indexPath.row];
//將單元格的主文字內容賦值
cell.textLabel.text=str;
return cell;
}