How to hide and show keyboard with same button
I have UITextField
which becomeFirstResponder
when app starts. Then, I have a UIButton
which resignFirstRespo开发者_开发知识库nder
when press it.
How to hide and show keyboard with same button? Is it possible?
Based on what you seem to need, the following code should have the same button both hide and show the keyboard for the textField
if ([textField isFirstResponder]) {
[textField resignFirstResponder];
} else {
[textField becomeFirstResponder];
}
edit
You can also put in code to alter the title of the button in the if loop.
The appropriate place to put the code to alter the title of the button would in the textField's delegate methods -textFieldDidBeginEditing:
and -textFieldDidEndEditing:
-(IBAction) buttonPressed:(id) sender {
UIButton *button = (UIButton *) sender;
button.selected = !button.selected;
if (button.selected) {
// show the keyboard.
[textField becomeFirstResponder];
}else {
// Hide the keyboard.
[textField resignFirstResponder];
}
}
mytest.h
IBOutlet UITextField *myTextField;
IBOutlet UIButton *myButton
- (IBAction) showHideKeyBoard:(id)sender;
mytest.m
-(IBAction) showHideKeyBoard:(id) sender {
if (myButton.selected) {
// show the keyboard.
[myTextField becomeFirstResponder];
[myButton setTitle:@"Hide" forState:UIControlStateNormal];
myButton.selected = NO;
}else {
// Hide the keyboard.
[myTextField resignFirstResponder];
[myButton setTitle:@"Show" forState:UIControlStateNormal];
myButton.selected = YES;
}
}
精彩评论