有两种可能的方案来解决您的问题:
1. 如果您有一个静态的UITableView,即所有单元格都在XIB或Storyboard中设置,则无法插入或删除单元格,因为整个表视图是通过接口生成器进行配置的,因此无法修改。
解决方法是在接口生成器中配置所有单元格(包括稍后需要显示的单元格),然后在运行时设置它们的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row == 0)
return _firstRowVisible ? 44 : 0;
return 44;
}
- (IBAction)showOrHideEmailField:(id)sender
{
_firstRowVisible = !_firstRowVisible;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView reloadData];
}
2. 如果您有动态单元格,可以在Interface Builder中设置它们的外观,为每个单元格类型设置自己的重用标识符。然后,在代码中,在-tableView:cellForRowAtIndexPath:
中,通过将相应的单元格标识符传递给UITableView的-dequeueReusableCellWithIdentifier:forIndexPath:
来指定您要使用哪种单元格,并适当地设置您的单元格。
为了使用-insertRowsAtIndexPaths:withRowAnimation:
,您需要先更新数据源,以使您的视图与模型同步。
对于您的情况,以下代码可能会起作用:
@property (assign, nonatomic) NSInteger numberOfEmailFields;
#pragma mark - Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
case 0:
return 6;
case 1:
return self.numberOfEmailFields + 1;
default:
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
case 0:
{
switch (indexPath.row) {
case 0:
{
static NSString *CellIdentifier = @"MyCell";
return [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
}
...
default:
break;
}
break;
}
default:
break;
}
return nil;
}
- (IBAction)addEmailField:(id)sender
{
self.numberOfEmailFields++;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
我使用动态单元格的方法为您创建了一个示例项目,下载链接在
此处。
请注意,要向表视图添加单元格,您需要使用第二种情况,也就是使用动态单元格。这乍一看似乎更加繁琐,但这种方法在未来扩展和修改时更加方便。