好的,我不知道如何使用 Storyboards,但如果您愿意接受这种类型的答案,我确实知道如何用纯代码做类似的事情。
对于简单的表格视图,您需要遵循两个一般规则:
1)告诉表格需要显示多少行
2)告诉表格您需要在每个单元格中呈现哪些元素
表中的行数通常由在视图控制器的 .h 文件中声明的数组中有多少元素来定义。
就像是
// View Controller header file (.h file)
@interface
{
...
NSMutableArray *arrOfItems;
}
然后在您的实现文件中,将食物添加到数组中,保存 Core Data 上下文,然后从 Core Data 执行获取并将结果存储到类变量数组中:
// this method gets called when your button is pressed
-(void)addFoodToList
{
Food *food = [NSEntityDescription insertNewObjectForEntityForName:@"Food"
food.name = foodToListNameTextField.text;
[managedObjectContext save:nil];
// for simplicity sake, we're doing a simple table reload
[self fetchData]; // see below
[myTableView reloadData]; // reloads the table to include the newly added food
}
-(void)fetchData
{
// core data fetch request of all items we want to display in the list
arrOfItems = [managedObjectContext executeFetchRequest:request .... ];
}
请注意,您应该在此表视图委托方法中返回类变量数组中的项目数:
// View Controller implementation file (.m file)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(int)section
{
// after adding the item to your arrOfItems and then doing a fetch request
// earlier (see above code), this next statement would return the correct value
return [arrOfItems count];
}
剩下要做的就是在您的 UITableViewCellForRow 方法中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString cellID = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithID:cellID];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithTableViewCellStyle:UITableViewCellStyleDefault reusableIdentifier:cellID] autorelease];
// init your element foodItemLabel
foodTitleLabel = [[UILabel alloc] initWithFrame:...];
foodTitleLabel.tag = 1;
[cell.contentView addSubview:foodTitleLabel];
[foodTitleLabel release];
}
foodTitleLabel = (UILabel *)[cell.contentView viewWithTag:1];
FoodItem *foodItem = (FoodItem *)[arrOfItems objectAtIndexPath:indexPath.row];
// display the food name
foodTitleLabel.text = foodItem.title;
return cell;
}