iOS中只让textField使用键盘通知的实例代码
程序员文章站
2023-12-21 12:32:52
代码:
#import "viewcontroller.h"
@interface viewcontroller ()
@end
@implementati...
代码:
#import "viewcontroller.h" @interface viewcontroller () @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; // do any additional setup after loading the view, typically from a nib. //为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 //键盘事件 - (void)keyboardwillshow:(nsnotification *)notification { nsdictionary *info = [notification userinfo]; // keyboardheight 为键盘高度 cgsize keyboardsize = [[info objectforkey:uikeyboardframeenduserinfokey] cgrectvalue].size; [self animateviewwithkeyboardheight:keyboardsize.height]; } - (void)keyboardwillhide:(nsnotification *)notification { [self animateviewwithkeyboardheight:0.0]; } - (void)animateviewwithkeyboardheight:(cgfloat)keyboardheight { nstimeinterval animationduration = 0.3f; cgfloat height = self.view.bounds.size.height; cgfloat width = self.view.bounds.size.width; cgfloat topsize = 0.0; cgfloat viewh = self.view.frame.size.height-64; cgfloat deviceheight = [uiscreen mainscreen].bounds.size.height; cgfloat animateh = deviceheight - viewh - keyboardheight; if (animateh >= 0) { topsize = 0; cgrect torect = cgrectmake(0, topsize, width, height); self.view.frame = torect; } else { topsize = animateh; cgrect torect = cgrectmake(0, topsize, width, height); [uiview animatewithduration:animationduration animations:^{ self.view.frame = torect; }]; } } #pragma -mark -uitextfieldtext notification //增加键盘事件 -(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]; } //移除键盘事件 -(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
总结
以上所述是小编给大家介绍的ios中只让textfield使用键盘通知的实例代码,希望对大家有所帮助