您的位置:首页 > 移动开发 > IOS开发

iOS第三方键盘高度获取方法

2015-05-13 16:46 627 查看

ios8允许第三方键盘使用后,键盘的高度经常不准确,怎么破,不废话,上代码。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UITextField *textField;

@end

@implementation ViewController

#pragma mark - lifeCycle

- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self.view addSubview:self.textField];
[self adjustFrame];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextFieldFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

- (void)adjustFrame
{
_textField.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds) - 40, CGRectGetWidth(self.view.bounds), 40);
}

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

#pragma mark - privateMethod

- (void)changeTextFieldFrame:(NSNotification *)noti
{
NSDictionary *userInfo = noti.userInfo;

[UIView animateWithDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
NSDictionary* d = [noti userInfo];

#pragma mark - 获取键盘frame

CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect frame = self.textField.frame;
frame.origin.y = CGRectGetMinY(r) - CGRectGetHeight(frame);
self.textField.frame = frame;
}];

}

#pragma mark - 触屏事件

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.textField resignFirstResponder];
}

#pragma mark - get

- (UITextField *)textField
{
if (_textField == nil) {
_textField = [[UITextField alloc] init];
_textField.backgroundColor = [UIColor lightGrayColor];
}
return _textField;
}

@end


该段代码的核心: CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];

用这段话可以比较准确的监听到键盘的高度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: