During the development process, we often encounter a problem: when we select the input box, the keyboard jumps out and overwrites our input box. The problem we need to solve is: move the input box up so that it is above the keyboard:
Prerequisites:
Declare a textfield in your h file
@property (retain, nonatomic) IBOutlet UITextField *textView;
First, the viewdidload method is as follows:
- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasHidden:) name:UIKeyboardDidHideNotification object:nil];}
In this method, we call two methods: processing the listening event when the keyboard is displayed, and processing the listening event when the keyboard disappears.
(1) Handling of listening events during keyboard display
-(void)keyboardwasShown:(NSNotification *) notify{ CGRect frame = [self.view frame]; if ([[notify name]isEqualToString:UIKeyboardDidShowNotification]) { [UIView animateWithDuration:0.3 animations:^{ self.view.frame = frame; }completion:^(BOOL finished) { // }]; } NSDictionary *info = [notify userInfo]; NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyBoardSize = [aValue CGRectValue].size; CGRect rect = self.textView.frame; rect.origin.y = self.view.frame.size.height - keyBoardSize.height - rect.size.height; self.textView.frame = rect; }
(2) handling of listening events when the keyboard disappears
-(void) keyboardwasHidden:(NSNotification *) notify{ NSDictionary *info = [notify userInfo]; NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; CGSize keyBoardSize = [aValue CGRectValue].size; CGRect rect = self.textView.frame; rect.origin.y = self.view.frame.size.height - rect.size.height; self.textView.frame = rect;}