iOS中只让textField使用键盘通知的实例代码
代码:
#import"ViewController.h" @interfaceViewController() @end @implementationViewController -(void)viewDidLoad{ [superviewDidLoad]; //Doanyadditionalsetupafterloadingtheview,typicallyfromanib. //为textField增加键盘事件 [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(addKeyboardNoti)name:UITextFieldTextDidBeginEditingNotificationobject:nil]; [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(removeKeyboardNoti)name:UITextFieldTextDidEndEditingNotificationobject:nil]; } #pragma-mark-keyboardnotificatin //键盘事件 -(void)keyboardWillShow:(NSNotification*)notification{ NSDictionary*info=[notificationuserInfo]; //keyboardHeight为键盘高度 CGSizekeyboardSize=[[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size; [selfanimateViewWithKeyboardHeight:keyboardSize.height]; } -(void)keyboardWillHide:(NSNotification*)notification{ [selfanimateViewWithKeyboardHeight:0.0]; } -(void)animateViewWithKeyboardHeight:(CGFloat)keyboardHeight{ NSTimeIntervalanimationDuration=0.3f; CGFloatheight=self.view.bounds.size.height; CGFloatwidth=self.view.bounds.size.width; CGFloattopSize=0.0; CGFloatviewH=self.view.frame.size.height-64; CGFloatdeviceHeight=[UIScreenmainScreen].bounds.size.height; CGFloatanimateH=deviceHeight-viewH-keyboardHeight; if(animateH>=0){ topSize=0; CGRecttoRect=CGRectMake(0,topSize,width,height); self.view.frame=toRect; }else{ topSize=animateH; CGRecttoRect=CGRectMake(0,topSize,width,height); [UIViewanimateWithDuration:animationDurationanimations:^{ self.view.frame=toRect; }]; } } #pragma-mark-UITextFieldTextNotification //增加键盘事件 -(void)addKeyboardNoti { NSLog(@"------addKeyboardNoti-------"); [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil]; [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil]; } //移除键盘事件 -(void)removeKeyboardNoti { NSLog(@"------removeKeyboardNoti---------"); [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillShowNotificationobject:nil]; [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil]; } -(void)didReceiveMemoryWarning{ [superdidReceiveMemoryWarning]; //Disposeofanyresourcesthatcanberecreated. } @end
总结
以上所述是小编给大家介绍的iOS中只让textField使用键盘通知的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!