簡體   English   中英

Obj-C-點擊單元格時向TableView添加新行?

[英]Obj-C- Add new row to TableView when cell is tapped?

我有一個表格視圖,允許用戶在點擊現有行時將項目(一行)添加到發票(表格視圖)中。 也就是說,我似乎無法添加一個空行,因為我的代碼正在嘗試使用我指定數組中的數據設置單元格中的信息,但自然地,數組中的計數與我的數據源不同(如我所願計數為+1)。

例如,即使我的數組中只有 2 個字典,我也想返回 3 個單元格,並且第三個單元格應該為空。

我想要這個,因為第三個單元格允許我的用戶填寫空字段,而前兩行中的字段填充了他們已經輸入的數據。 這是我現在嘗試返回額外行的方式,但如上所述,由於數組中返回的字典不平衡,它會使我的應用程序崩潰。

到目前為止,這是我的代碼:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.allItems = [[NSMutableArray alloc] init];
    self.itemDetails = [[NSMutableDictionary alloc] init];

}

//TableView delegates
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
   
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return self.allItems.count + 1;

}



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

        static NSString *ClientTableIdentifier = @"InvoiceDetailsTableViewCell";
        
       InvoiceDetailsTableViewCell *cell = (InvoiceDetailsTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:ClientTableIdentifier];
        
        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"InvoiceDetailsTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            
        }
    
    if (self.allItems.count == 0) {
        
    } else {
        
        cell.itemName.text = [self.allItems valueForKey:@"Item Name"][indexPath.row];
     
        
    }
    
        return cell;
        
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
   InvoiceDetailsTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   
    NSString *itemTitle = cell.itemName.text;
    NSString *itemDescrip = cell.itemDescrip.text;
    NSString *itemCost = cell.itemCost.text;
    NSString *itemTax = cell.itemTax.text;
    
    
    [self.itemDetails setValue:itemTitle forKey:@"Item Name"];

    [self.itemDetails setValue:itemDescrip forKey:@"Item Description"];
    
    [self.itemDetails setValue:itemCost forKey:@"Item Cost"];
  
    [self.itemDetails setValue:itemTax forKey:@"Item Tax Rate"];

    [self.allItems addObject:self.itemDetails];
    
    [self.tableView reloadData];

}

一個重要的問題是這樣一行:

cell.itemName.text = [self.allItems valueForKey:@"Item Name"][indexPath.row];

由於您的行數超過了數組中的項目數,因此您需要在訪問數組之前檢查行號:

NSInteger row = indexPath.row;
if (row < self.allItems.count) {
    cell.itemName.text = self.allItems[row][@"Item Name"]; // personally, I’d get row first, and then keyed value second
} else {
    cell.itemName.text = @"";
}

您要檢查以確保當前行不是最后(空白)行。

暫無
暫無

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

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