【发布时间】:2014-04-08 06:51:59
【问题描述】:
我创建了一个自定义UITableViewCell 类,该类将UITextfield 嵌入到每个单元格中,在addItemTableViewController 中,我想在所有UITextField-embededd 单元格中获取文本值并创建一个新模型对象,但我遇到问题:
cellForRowAtIndexPath 为不可见的单元格返回 nil,在我向下滚动到我的 tableview 的底部然后点击添加按钮后,前几行的 textField 文本值变为 null。
无论如何我可以解决这个问题吗?我已经在谷歌上搜索了几个小时,但仍然没有找到答案。
这是我的 addItemTableViewController 代码:
- (IBAction)doneAdd:(UIBarButtonItem *)sender {
[self.delegate addItem:[self newItem]];
}
- (NSMutableArray *)newItem
{
NSMutableArray *newItem = [[NSMutableArray alloc] init];
for (int i = 0; i < [_appDelegate.title count]; i ++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UPFEditableUITableViewCell *cell = (UPFEditableUITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
NSLog(@"%@", cell.editField.text);
//[newItem addObject:cell.editField.text]; //this does not work as null cannot be added into a array
}
NSLog(@"%@", newItem);
return newItem;
}
这是我的自定义 UITableViewCell 类实现
#import "UPFEditableUITableViewCell.h"
@implementation UPFEditableUITableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.editField = [[UITextField alloc] initWithFrame:CGRectZero];
[self.contentView addSubview:self.editField];
}
return self;
}
- (void)layoutSubviews
{
if ([self.detailTextLabel.text length] == 0) {
self.detailTextLabel.text = @" ";
}
[super layoutSubviews];
// place the edit field in the same place as the detail text field, give max width
self.editField.frame = CGRectMake(self.detailTextLabel.frame.origin.x, self.detailTextLabel.frame.origin.y, self.contentView.frame.size.width-self.detailTextLabel.frame.origin.x, self.detailTextLabel.frame.size.height);
}
- (void)showEditingField:(BOOL)show
{
self.detailTextLabel.hidden = YES;
self.editField.text = self.detailTextLabel.text;
}
@end
【问题讨论】:
-
你不能通过 Cell 访问文本字段,在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;您应该相应地为每个 textField 提供标签,然后您就可以轻松获取 textFields
标签: ios objective-c uitableview uitextfield