设为首页 加入收藏

TOP

UI键盘通知(一)
2017-10-12 12:57:52 】 浏览:10516
Tags:键盘 通知

 

 

#import "ViewController.h"

 

@interface ViewController ()

@property (nonatomic,strong) UITextField *tf;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    _tf = [[UITextField alloc]initWithFrame:CGRectMake(10, self.view.bounds.size.height - 40, 300, 30)];

    _tf.borderStyle = UITextBorderStyleRoundedRect;

    [self.view addSubview:_tf];

    

    /*

    通知中心(单例)

    通知中心是一对多的,即同一个广播可以被多个收音机接收

     代理是一对一

     作用:1.用来接收广播和发起广播

                 2.用通知的名字作为频道

     */

    /*

    参数一:响应的类

     参数二:类中响应的方法

     参数三:通知的名字(即频道)

     参数四:接收类型 [注意]nil代表任何类型

     */

    //:UIKeyboardWillShowNotification接收键盘将要显示的通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    

    

    //UIKeyboardWillHideNotification接收键盘将要隐藏的通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

}

#pragma mark - UIKeyboardWillHideNotification

//键盘将要隐藏

-(void)keyBoardWillHide:(NSNotification *)noti

{

     //noti.userInfo是一个字典,大家可以输出来看看字典里面包含了什么

    //NSLog(@"%@",noti.userInfo);

 

    //获得弹下去后的坐标[注意是弹下后的]

    CGRect keyBoardEndFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    //NSLog(@"--%@",NSStringFromCGRect(keyBoardEndFrame));

    [UIView animateWithDuration:2 animations:^{

        //改变文本框的位置,让它跟着键盘一起弹起来

        CGRect tfRext = _tf.frame;

        tfRext.origin.y = keyBoardEndFrame.origin.y-_tf.bounds.size.height-10;

        _tf.frame = tfRext;

    }];

}

 

#pragma mark - UIKeyBoard notification

//接收到的是通知,所以参数用NSNotification

//键盘将要显示

-(void)keyBoardWillShow:(NSNotification *)noti

{

    CGRect keyBoardFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    //可以通过以下方法输出CGRect

    //NSStringFromCGRectCGRect转化为字符串的方式获取Frame

    //NSLog(@"%@",NSStringFromCGRect(keyBoardFrame));

    

    //获取键盘的动画持续时间

    //CGFloat keyBoardDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    

    [UIView animateWithDuration:2 animations:^{

        CGRect tfRect = _tf.frame;

        tfRect.origin.y = keyBoardFrame.origin.y - _tf.bounds.size.height -10;

        _tf.frame = tfRect;

    }];

    

}

#pragma mark - 当手指触碰屏幕任何一地方时被调用

-(void)touchesBegan:(NSSet<UIT

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇UIScrollView 滑动试图 下一篇Xcode的代码片段快捷方式-Code Sn..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目