当我专注于 UITextField 控件时,我将按钮添加为子视图。当我从 UITextField 中移除焦点时,我移除了添加按钮。这在 UITextField 中有一些文本时有效。但是当没有文本时,按钮不会消失。
Q. How can I remove the UIButton from UITextField when the UITextField is empty.
I also want to be able to show *default* placeholder-text for UITextField when add button is removed.
这是我添加和删除取消按钮作为子视图的代码
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
if(textField == txtToEmailAddress)
{
txtToEmailAddress.rightView = button;
txtToEmailAddress.rightViewMode = UITextFieldViewModeAlways;
[button addTarget:self action:@selector(AddEmailAddress:) forControlEvents:UIControlEventTouchUpInside];
[self.txtToEmailAddress addSubview:button];
}
if(textField == txtCallPhoneNum)
{
txtCallPhoneNum.rightView = button;
txtCallPhoneNum.rightViewMode = UITextFieldViewModeAlways;
[button addTarget:self action:@selector(AddPhoneNumber:) forControlEvents:UIControlEventTouchUpInside];
[self.txtCallPhoneNum addSubview:button];
}
if(textField == txtTextNumbers)
{
txtTextNumbers.rightView = button;
txtTextNumbers.rightViewMode = UITextFieldViewModeAlways;
[button addTarget:self action:@selector(AddTextNumber:) forControlEvents:UIControlEventTouchUpInside];
[self.txtTextNumbers addSubview:button];
}
return YES;
}
- (BOOL)textFieldDidEndEditing:(UITextField *)textField
{
UIButton *button = nil;
if(textField == txtToEmailAddress)
{
button = (UIButton *)[txtToEmailAddress.subviews objectAtIndex:1];
}
if(textField == txtCallPhoneNum)
{
button = (UIButton *)[txtCallPhoneNum.subviews objectAtIndex:1];
}
if(textField == txtTextNumbers)
{
button = (UIButton *)[txtTextNumbers.subviews objectAtIndex:1];
}
if (button != nil)
{
button.hidden = YES;
[button removeFromSuperview];
}
return YES;
}
这是需要消失的空 UITextField 中的添加按钮。