您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS UITableView 基礎:資料源、代理與載入更多

編輯:iOS 相關資訊

UITableView 是 iOS 中最常見的列表元件。它透過 dataSource 提供資料,透過 delegate 處理互動。以下是一個基礎範例。

建立表格與資料

items = [NSMutableArray arrayWithObjects:@"AA", @"BB", @"CC", @"DD", @"EE", nil];

UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];

回傳列數

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return items.count + 1;
}

建立 Cell

使用固定 identifier 可以讓 Cell 被重複使用,提升效能。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }

    if (indexPath.row == items.count) {
        cell.textLabel.text = @"載入更多";
    } else {
        cell.textLabel.text = items[indexPath.row];
    }

    return cell;
}

處理選取

若點擊最後一列的載入更多,可以觸發非同步載入。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == items.count) {
        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
    }
}

背景載入與更新

- (void)loadMore {
    NSArray *more = @[@"11", @"22", @"33"];
    [self performSelectorOnMainThread:@selector(appendItems:) withObject:more waitUntilDone:NO];
}

- (void)appendItems:(NSArray *)data {
    for (NSUInteger index = 0; index != data.count; index++) {
        [items addObject:data[index]];
    }
    [tableView reloadData];
}

這個範例展示了 UITableView 的基本生命週期:建立資料、回傳列數、配置 Cell、處理點擊,以及透過背景佇列載入更多資料。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved