UITableView的基本使用方法

UITableView是這樣使用滴:

#define SCREEN_WIDHT [[UIScreen mainScreen] bounds].size.width

需要實現倆個代理:

<UITableViewDataSource, UITableViewDelegate>

// 存放Cell上各行textLabel

@property (nonatomic, copy)NSMutableArray * textLabelArray;


//設置要顯示的數據

    NSMutableArray *array =[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];

    _textLabelArray = array;

    

    UITableView *tableview = [[UITableView alloc]initWithFrame:CGRectMake(10, 74, SCREEN_WIDHT-20, 200) style:UITableViewStylePlain];

    tableview.delegate = self;

    tableview.dataSource = self;

   [self.view addSubview:tableview];

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // 定義一個標識符,是系統用來匹配table各行cell的判斷標準

    static NSString *cellIdent = @"cellIdent";

    // 從緩存隊列中取出複用的cell

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];

    // 如果隊列中cell爲空,即無複用的cell,則對其進行初始化

    if (cell==nil) {

        // 初始化

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];

        // 定義其輔助樣式

        cell.accessoryType = UITableViewCellStyleDefault;

    }

    // 設置cell上文本內容

    cell.textLabel.text = [_textLabelArray objectAtIndex:indexPath.row];

    

    return cell;

}


//可以爲不同的分區設置不同的頁眉

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return @"好吧這是頁眉";

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // 取消選中效果,點擊後恢復原狀

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    

    NSLog(@"點擊了第%ld",(long)indexPath.row+1);

}

//可以刪除

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}


// 設置刪除按鈕標題

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return @"刪除";

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 從數據中刪除

    [self.textLabelArray removeObjectAtIndex:indexPath.row];

    

    // 從列表中刪除

    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章