【问题标题】:UITextField content gets lost when the view is scrolled off the screen当视图滚动出屏幕时,UITextField 内容会丢失
【发布时间】:2012-07-08 03:36:20
【问题描述】:

我有一个包含 UITextField 的自定义 UITableViewCell 原型。在最后一部分填充 UITextField 时,我会自动添加新单元格。如果有更多的部分不适合一个屏幕,我添加了另一个,它会被第一部分的值填充,第一部分的输入被清空!

截图:

相关代码:

@implementation TMNewTripPeopleViewController

@synthesize sectionsCount = _sectionsCount;
@synthesize firstCellShowed = _firstCellShowed;

- (int) sectionsCount
{
    if (_sectionsCount == 0) {
        _sectionsCount = 1;
    }
    return _sectionsCount;
}

- (IBAction)inputChanged:(id)sender {
    UITextField* input = (UITextField*) sender;
    NSIndexPath* indexPathName = [NSIndexPath indexPathForRow:0 inSection:input.tag - 1];
    UITableViewCell* cellName = [self.tableView cellForRowAtIndexPath:indexPathName];

    if (input == [cellName viewWithTag:input.tag]) {
        // last name input - add next section?
        if (input.tag == self.sectionsCount) {
            if (input.text.length > 0) {
                self.sectionsCount++;
                [self.tableView insertSections:[NSIndexSet indexSetWithIndex:self.sectionsCount - 1] withRowAnimation:UITableViewRowAnimationTop];
            }
        }
    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionsCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"PersonName";
    if (indexPath.row % 2 == 1) {
        CellIdentifier = @"PersonEmail";
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UITextField* input = (UITextField*) [cell viewWithTag:indexPath.section + 1];
    if (indexPath.row == 0 && indexPath.section == 0 && !self.firstCellShowed) {
        [input becomeFirstResponder];
        self.firstCellShowed = YES;
    }

    [cell viewWithTag:1].tag = indexPath.section + 1;

    return cell;
}

@end

【问题讨论】:

    标签: objective-c xcode uitableview cocoa-touch uitextfield


    【解决方案1】:

    我在您的实现中没有看到tableView:willDisplayCell:forRowAtIndexPath:。您通常在此方法中设置单元格的显示值。

    当您使用dequeueReusableCellWithIdentifier(并且您几乎总是应该)时,您的单元格将在表格视图滚动时被重用。如果您不更新它们在willDisplayCell 中的值,那么它们将显示它们在重用之前具有的任何值(如果有的话)。

    【讨论】:

    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多