1

我有一个标准的 UITextField,已添加到 UITableViewCell 中,每当我去编辑它时,其中的文本都不会清除。我试过放置一个占位符,编辑时也不会清除。这是怎么回事?

if (indexPath.row == 1) {
        cell.textLabel.text = @"Device ID";
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        deviceID = [[UITextField alloc] initWithFrame:CGRectMake(115, 11, 388, 22)];
        deviceID.delegate = self;
        deviceID.adjustsFontSizeToFitWidth = YES;
        deviceID.font = [UIFont boldSystemFontOfSize:15];
        deviceID.textColor = [UIColor blackColor];
        deviceID.autocorrectionType = UITextAutocorrectionTypeNo;
        deviceID.autocapitalizationType = UITextAutocapitalizationTypeNone;
        deviceID.textAlignment = NSTextAlignmentLeft;
        deviceID.clearButtonMode = UITextFieldViewModeWhileEditing;
        deviceID.keyboardType = UIKeyboardTypeDefault;
        deviceID.backgroundColor = [UIColor clearColor];
        deviceID.delegate = self;
        deviceID.clearsOnBeginEditing = YES;
        deviceID.text = [[NSUserDefaults standardUserDefaults] objectForKey:DEVICE_ID];
        [deviceID setEnabled:YES];
        [cell addSubview:deviceID];
    }

- (BOOL)textFieldShouldClear:(UITextField *)textField {

    return YES;
}
4

4 回答 4

4

cellForRowAtIndexPath每当调用时,您都会将相同文本字段的多个实例添加到单元格中。在其中创建文本字段viewDidLoad并添加到此单元格。它应该工作。

另一种方法是继承你的子类UITableViewCell并将这个 textFiled 添加为它的init方法中的属性。然后您可以将值设置为cell.textField.text = @"some value";

如果在 中添加这一行cellForRowAtIndexPath

deviceID = [[UITextField alloc] initWithFrame:CGRectMake(115, 11, 388, 22)];

每当重新加载表视图时都会调用它,并且您将丢失以前文本字段的引用。因此,您需要确保只创建一个文本字段并将其添加到 tableview 单元格。这也将确保您在单元格中只创建了一个文本字段。

于 2013-01-05T20:16:05.623 回答
1

如果您尝试此委托方法会怎样:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
   [textField setText:@""];
}
于 2013-01-05T20:11:27.910 回答
0

我在另一篇文章中发现了以下内容(通常与视图有关):

[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

并转换为:

[cell.contentView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

完美地解决了这个线程中的问题。

于 2013-01-29T06:18:01.910 回答
0

你可以用这个

[deviceID removeFromSuperview];
devideID = nil;
deviceID = [[UITextField alloc] initWithFrame:CGRectMake(115, 11, 388, 22)];
...

虽然接受的答案有效,但如果您不想将必须创建 UITextField 的责任委托给 ViewController,请使用此

于 2014-06-17T19:56:23.820 回答