Reputation: 1976
I have a standard UITextField that I have added to a UITableViewCell and whenever I go to edit it, the text that is in it will not clear out. I have tried placing a placeholder and that too will not clear when editing. What's going on?
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;
}
Upvotes: 1
Views: 1517
Reputation: 8651
You can use this
[deviceID removeFromSuperview];
devideID = nil;
deviceID = [[UITextField alloc] initWithFrame:CGRectMake(115, 11, 388, 22)];
...
While the accepted answer works, if you don't want to delegate the responsibility to the ViewController of having to create the UITextField then use this
Upvotes: 0
Reputation: 3541
I found the following in another post (pertaining to views, generally):
[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
and converted to this:
[cell.contentView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
Works perfectly to resolve problem in this thread.
Upvotes: 0
Reputation: 23278
You are adding multiple instances of same textfield on to the cell whenever cellForRowAtIndexPath
is called. Create textfield in viewDidLoad
and add on to this cell. It should work.
An alternate way is to subclass your UITableViewCell
and add this textFiled as a property of that in its init
method. Then you can set value as cell.textField.text = @"some value";
If you add this line in cellForRowAtIndexPath
,
deviceID = [[UITextField alloc] initWithFrame:CGRectMake(115, 11, 388, 22)];
It will get called whenever the table view is reloading and you will lose the references of previous textfields. So you need to make sure that you are creating only one textfield and adding it to tableview cell. This will also make sure that you have only a single textfield created in the cell.
Upvotes: 4
Reputation: 21808
What if you try this delegate method:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[textField setText:@""];
}
Upvotes: 1