我有一个tableview,允许用户添加一个项目(一行)到发票(tableview)当一个现有的行被点击。也就是说,我似乎不能添加空行,因为我的代码试图将单元格中的信息设置为来自指定数组的数据,但自然地,数组中的计数与我的数据源不同(因为我希望计数为+1)。
。我想返回3个单元格,即使我的数组中只有2个字典,第三个单元格应该是空的。
我需要这个,因为第三个单元格允许我的用户填写空字段,而前两行的字段使用他们已经输入的数据填充。下面是我现在如何尝试返回额外的行,但如上所述,由于数组中返回的字典不平衡,它使我的应用程序崩溃。
下面是目前为止的代码:- (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 = @"";
}
您需要检查以确保当前行不是最后(空白)行。