【发布时间】:2009-07-28 20:07:58
【问题描述】:
我正在尝试在 iPhone 上的照片库中创建一个类似于 YouTube 视频上传器视图的表格视图。
这是基本设置。
我创建了一个包含 UITextField 的自定义 UITableViewCell。在我的表格中显示单元格效果很好,我可以毫无问题地编辑文本。我创建了一个事件挂钩,以便我可以查看文本字段中的文本何时发生更改。
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]
我想做的就是这个。当用户第一次编辑文本时,我想在当前单元格下方的表格视图中插入一个新单元格(newIndexPath 在正确位置之前计算):
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationBottom];
[self.tableView endUpdates];
问题是当我运行单元格插入代码时,单元格被创建,但文本字段的文本短暂更新,但随后键盘被关闭,文本字段被设置回空字符串。
任何帮助都会很棒!我整天都在为这个问题头疼。
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return 2;
else
return self.tags.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
cell = (SimpleTextFieldTableCell *)[tableView dequeueReusableCellWithIdentifier:tagCellIdentifier];
if (cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:@"SimpleTextFieldTableCell" owner:nil options:nil] lastObject];
}
((SimpleTextFieldTableCell *)cell).textField.delegate = self;
((SimpleTextFieldTableCell *)cell).textField.tag = indexPath.row;
((SimpleTextFieldTableCell *)cell).textField.text = [self.tags objectAtIndex:indexPath.row];
[((SimpleTextFieldTableCell *)cell).textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
- (void)textFieldDidChange:(id)sender
{
UITextField *textField = sender;
[self.tags replaceObjectAtIndex:textField.tag withObject:textField.text];
if (textField.text.length == 1)
{
[textField setNeedsDisplay];
[self addTagsCell];
}
}
- (void)addTagsCell
{
NSString *newTag = @"";
[self.tags addObject:newTag];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:self.tags.count - 1 inSection:1];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationBottom];
[self.tableView endUpdates];
}
【问题讨论】:
-
如果您注释掉插入,文本字段是否为空白?
-
不,如果没有插入,文本字段会保留输入的文本。只有在插入单元格时,文本才会消失。
-
上面的 tagCellIdentifier 设置为“SimpleTextFieldTableCell”,这是我在 Interface Builder 中为单元格设置的标识符。
标签: iphone uitableview uitextfield