Code:
#import "" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //Add keyboard event for textField [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addKeyboardNoti) name:UITextFieldTextDidBeginEditingNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeKeyboardNoti) name:UITextFieldTextDidEndEditingNotification object:nil]; } #pragma -mark -keyboard notificatin //Keyboard event- (void)keyboardWillShow:(NSNotification *)notification { NSDictionary *info = [notification userInfo]; // keyboardHeight is the keyboard height CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; [self animateViewWithKeyboardHeight:]; } - (void)keyboardWillHide:(NSNotification *)notification { [self animateViewWithKeyboardHeight:0.0]; } - (void)animateViewWithKeyboardHeight:(CGFloat)keyboardHeight { NSTimeInterval animationDuration = 0.3f; CGFloat height = ; CGFloat width = ; CGFloat topSize = 0.0; CGFloat viewH = -64; CGFloat deviceHeight = [UIScreen mainScreen].; CGFloat animateH = deviceHeight - viewH - keyboardHeight; if (animateH >= 0) { topSize = 0; CGRect toRect = CGRectMake(0, topSize, width, height); = toRect; } else { topSize = animateH; CGRect toRect = CGRectMake(0, topSize, width, height); [UIView animateWithDuration:animationDuration animations:^{ = toRect; }]; } } #pragma -mark -UITextFieldText Notification //Add keyboard events-(void)addKeyboardNoti { NSLog(@"------addKeyboardNoti-------"); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; } //Remove keyboard event-(void)removeKeyboardNoti { NSLog(@"------removeKeyboardNoti---------"); [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
Summarize
The above is the example code in iOS that only allows textField to use keyboard notifications. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!