Reputation: 4606
what i am trying to do is do a custom clear button in a UITextField, currently i have got everything working except for the last part. Which is getting it to preform the clear action. However, i have not been able to work out how i can get it to clear, just the textField it is in.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[textField setTextColor:[UIColor colorWithRed:0.56f green:0.56f blue:0.56f alpha:1.00f]];
[textField setFont:[UIFont systemFontOfSize:14]];
textField.background = [UIImage imageNamed:@"whiteCell"];
UIButton *btnColor = [UIButton buttonWithType:UIButtonTypeCustom];
[btnColor addTarget:self action:@selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
btnColor.frame = CGRectMake(0, 0, 25, 25);
[btnColor setBackgroundImage:[UIImage imageNamed:@"clearBut"] forState:UIControlStateNormal];
textField.rightView = btnColor;
textField.rightViewMode = UITextFieldViewModeAlways;
[textField addSubview:btnColor];
return YES;
}
This is how i've created the button in the textField, and for it to only show when editing, as you can see i have it calling clearText
however i'm unsure how i can send the current textField name i am in to be cleared in the clearText
call.
I know I can do it the hard way, and define it individually for each of my textFields, but i'm sure there is an easier way to go about this, that i just haven't realized.
Upvotes: 2
Views: 1504
Reputation: 3595
Given that your button has been added to the text field as a sub-view you can get to the text field in the buttons superview property:
- (void) clearText:(UIButton*)sender
{
UITextField* textField = (UITextField*)sender.superview;
textField.text = nil;
}
Upvotes: 0
Reputation: 9703
I suggest subclassing UITextField
. This will not allow you to lay out the button in a Storyboard, but in Code or as a .nib file should work. Of course you can use the UITextfield
subclass in a storyboard.
Inside the subclass add a UIButton
as a subview and in its action method call:
self.text = @""
Let me know if you have any further questions.
Upvotes: 1