在App開放中我們經常會使用到UITabbleView,常用于數據展示。那么使用時不得不引入兩個代理方法<UITableViewDataSource,UITableViewDelegate>。 下面我們來簡單的創建一個TableView并介紹下其基本屬性。 @property (nonatomic,strong) UITableView * myTable; //聲明對象
建議使用懶加載的方式創建,可以節省內存,然后再外部請求到數據后用.語法調用。
- (UITableView *)myTable{ if (!_myTable) { _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64-44) style:UITableViewStylePlain]; //初始化對象并設定大小和風格樣式 _myTable.delegate = self; _myTable.dataSource = self; //設置代理 _myTable.showsHorizontalScrollIndicator = NO; //不顯示水平滾動條 _myTable.showsVerticalScrollIndicator = NO; //不顯示豎直滾動條 _myTable.bounces = NO; //關閉彈性效果 } return _myTable; }
我們要在UITableView上展示數據,所以要有一個數據源,同理數據源也采用懶加載的方式。 @property (nonatomic,strong) NSMutableArray * dataSorce;
- (NSMutableArray *)dataSorce{ if (!_dataSorce) { _dataSorce = [[NSMutableArray alloc]init]; } return _dataSorce; }
下面開始設置代理方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _dataSorce.count; //返回cell的個數 }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 40; //返回cell的高度 }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString * string = @"patrcell"; PartCell * cell = [tableView dequeueReusableCellWithIdentifier:string]; if (!cell) { cell = [[PartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; //cell的復用及自定義cell的樣式 }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ }