聲明一個(gè)鍵盤高度屬性
@property (nonatomic, assign)CGSize kbSize;
在 viewDidLoad 中視圖注冊通知中心
[self registerForKeyboardNotifications];
pragma mark -- 注冊鍵盤的通知中心獲取鍵盤的高度
//注冊一個(gè)鍵盤的通知中心
- (void)registerForKeyboardNotifications{
//使用NSNotificationCenter 鍵盤出現(xiàn)時(shí)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
}
//實(shí)現(xiàn)當(dāng)鍵盤出現(xiàn)的時(shí)候計(jì)算鍵盤的高度大小。用于輸入框顯示位置
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
//kbSize鍵盤尺寸 (有width, height)
self.kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//鍵盤高度
NSLog(@"hight_hitht:%f",self.kbSize.height);
//self.view.frame = self.view.frame.size.height - self.kbSize.height;
CGRect currentFrame = self.view.frame;
CGFloat change =self.kbSize.height;
currentFrame.origin.y = currentFrame.origin.y - change ;
[UIView animateWithDuration:0.00000000001 animations:^{
self.view.frame = currentFrame;
}];
}`
// 視圖將要消失時(shí),移除通知中心
-(void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}