码迷,mamicode.com
首页 > 其他好文 > 详细

通过通知监听键盘的状态来改变View的位置

时间:2016-06-26 22:20:05      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>{
    UIView * _mainView;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 600)];
    [self.view addSubview:_mainView];
    _mainView.backgroundColor = [UIColor orangeColor];
    
    // 新建一个UITextField,位置及背景颜色随意写的。
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 40)];
    textField.delegate = self;
    textField.backgroundColor = [UIColor grayColor];
    
    [self.view addSubview:textField]; // 自定义的view
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPosition:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPosition:) name:UIKeyboardWillHideNotification object:nil];
}

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

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return  YES;
}

// 根据键盘状态,调整_mainView的位置

- (void)changeContentViewPosition:(NSNotification *)notification{
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 得到键盘弹出后的键盘视图所在y坐标
    CGFloat keyBoardEndY = value.CGRectValue.origin.y;
    // 键盘弹出所用时间
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    // 添加移动动画,使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{ [UIView setAnimationBeginsFromCurrentState:YES];
        // 对View设置转场动画方向 枚举类型
        [UIView setAnimationCurve:[curve intValue]];
        _mainView.center = CGPointMake(_mainView.center.x, keyBoardEndY - 20 - _mainView.bounds.size.height/2.0);  // keyBoardEndY的坐标包括了状态栏的高度,要减去

    }];
}

-(void)dealloc{
    //移除监听
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end

通过通知监听键盘的状态来改变View的位置

标签:

原文地址:http://www.cnblogs.com/flyter/p/5618622.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!