[iOS]利用通知实现监听系统键盘

//
//  ViewController.m
//  text
//
//  Created by 李东旭 on 16/1/22.
//  Copyright © 2016年 李东旭. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "ViewController.h"



@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITextView *textV = [[UITextView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:textV];
    
    // 1. 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘将要出现 UIKeyboardWillShowNotification
    // 键盘已经出现 UIKeyboardDidShowNotification
    // 键盘将要隐藏 UIKeyboardWillHideNotification
    // 键盘已经隐藏 UIKeyboardDidHideNotification
    
}

// 2. 键盘已经出现调用的触发方法
- (void)keyBoardChange:(NSNotification *)noti
{
    NSLog(@"%@", noti);
// 打印noti
    /*
     0x7f84584d1000 {name = UIKeyboardDidShowNotification; userInfo = {
// 键盘动画执行节奏
     UIKeyboardAnimationCurveUserInfoKey = 7;
     
// 键盘动画的时间
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     
// 键盘的bounds
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
     
// 键盘的起始center
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
     
// 键盘的结束center
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
     
// 键盘开始动画前的位置(也就是消失时)
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     
// 键盘结束动画后的位置(也就是弹出了)
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";

     UIKeyboardIsLocalUserInfoKey = 1;
     }}
     */
    
    // 3. 那么如何获取这个值呢
    NSDictionary *noKey = [noti userInfo];
    NSValue *value = noKey[@"UIKeyboardBoundsUserInfoKey"];
    // 注意,这个的value 是CGRect类型的(所以下面必须调用CGRectValue方法
    NSLog(@"%f", [value CGRectValue].size.height);
    
}


@end

有错误还忘您指出,如果这篇文章帮助到您了,或者您有什么建议和补充,都可以留言告诉我哦!

 

 

posted on 2016-01-25 17:14  M_Lee  阅读(684)  评论(0编辑  收藏  举报

导航