簡體   English   中英

用戶向表視圖控制器中的靜態單元格添加行/節

[英]User adding rows/sections to static cells in Table View Controller

我想創建一個類似於iPhone Contacts應用程序的“ New Contact”屏幕的屏幕。 在“添加電話”,“添加電子郵件”等旁邊沒有綠色的“ +”號。當用戶單擊這些時,會創建新的行(或者在“添加地址”的情況下,我想是新的部分)。

如何在Table View Controller中創建類似的行為?

謝謝,丹尼爾

這是一個如何向TableView添加行的示例:

// holding your data
NSMutableArray* data;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [data count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[data objectAtIndex:section] count];
}

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

    //if you want to add a section with one row:
    NSMutableArray *row = [[NSMutableArray alloc] init];
    [row addObject:@"Some Text"];
    [data addObject:row];
    [tableView reloadData];

    //if you want to add a row in the selected section:
    row = [data objectAtIndex:indexPath.section];
    [row addObject:@"Some Text"];
    [tableView reloadData];
}

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

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

    return cell;
}

Tableview中應該有一個新行。 下一步是用我們自己的數據替換“某些文本”。

這是我要采取的一般方法。

創建一個自定義tableview單元格,並使用類似的方法為其創建委托

-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell;

讓您的視圖控制器成為tableview單元的委托,並在觸發該操作時執行以下操作:

-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell
{
    NSIndexPath *oldIndexPath = [self.tableView indexPathForCell:cell];
    NSIndexPath *pathToInsert = [NSIndexPath indexPathForRow:(oldIndexPath.row + 1) inSection:oldIndexPath.section];

    [self.tableView beginUpdates];

    //now insert with whatever animation you'd like
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:pathToInsert] withRowAnimation:UITableViewRowAnimationAutomatic];


    [self.tableView endUpdates];
}

將“特殊”行的索引路徑添加到數組中,然后在cellForRow方法中檢查這是否是特殊行,並進行相應設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM