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.
unbutton をサブビューとして追加および削除するコードは次のとおりです
- (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 の追加ボタンです。