键盘管理-监听键盘事件及键盘出现或者隐藏时改变view的位置

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //监听键盘出现的事件
    /*
     addObserver 监听者
     selector 回调方法
     name 被监听事件(发布者发布的事件,nil代表所有事件)
     object 被监听者(发布者,nil代表所有发布者)
     
     过程:监听者 监听 发布者 所发布的事件,监听到事件后执行回调方法
     */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (IBAction)hiddenKeyboard:(id)sender {
    [self.view endEditing:YES];
}

- (void)keyboardShow:(NSNotification *)noti
{
    NSLog(@"%@",noti);
    /*
     {name = UIKeyboardWillShowNotification; userInfo = {
     UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 606.5}";
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 353.5}";
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
     }}

     */
    
    //键盘的frame值
    CGRect keyboardF = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //键盘的y值
    CGFloat keyboardY = keyboardF.origin.y;
    //动画时间
    CGFloat aniTime = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:aniTime animations:^{
        //改变view的Y值
        self.view.transform = CGAffineTransformMakeTranslation(0, keyboardY-480);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(ios,监听,键盘)