【发布时间】:2014-03-20 17:49:46
【问题描述】:
我想创建一个类似于 iPhone 联系人应用程序的“新联系人”屏幕的屏幕。 “添加电话”、“添加电子邮件”等旁边有绿色的小“+”号。当用户单击这些时,会创建新行(或者在“添加地址”的情况下,我想是新部分)。
如何在我的表视图控制器中创建类似的行为?
谢谢,丹尼尔
【问题讨论】:
标签: ios ios7 xcode5 uitableview
我想创建一个类似于 iPhone 联系人应用程序的“新联系人”屏幕的屏幕。 “添加电话”、“添加电子邮件”等旁边有绿色的小“+”号。当用户单击这些时,会创建新行(或者在“添加地址”的情况下,我想是新部分)。
如何在我的表视图控制器中创建类似的行为?
谢谢,丹尼尔
【问题讨论】:
标签: ios ios7 xcode5 uitableview
这是一个如何向 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 中应该有一个新行。下一步是用我们自己的数据替换“Some Text”。
【讨论】:
这是我会采取的一般方法。
创建一个自定义的 tableview 单元格并为其创建一个委托
-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell;
让您的视图控制器成为表格视图单元格的委托,当触发该操作时,请执行以下操作:
-(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 方法中检查这是否是特殊行并进行设置。
【讨论】: