2015-09-22 50 views

回答

7

您應該使用UIKeyboardWillChangeFrameNotification。另外,請確保將CGRect轉換爲正確的視圖,以供橫向使用。

集NSNotificationCenter在textFieldShouldBeginEditing

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; 

,寫這個方法。

- (void)keyboardWillChange:(NSNotification *)notification { 
    CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it! 
} 

在斯威夫特4

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil) 

KeyboardWillChange方法

@objc func keyboardWillChange(_noti:NSNotification) 
{ 
    let keyBoard = _noti.userInfo 
    let keyBoardValue = keyBoard![UIKeyboardFrameEndUserInfoKey] 
    let fram = keyBoardValue as? CGRect // this is frame 
} 
+0

完美答案,謝謝! –

+0

它是旋轉下的鍵盤矩形的處理,這是這個答案的重要部分。 – Abizern

4

註冊UIKeyboardWillShowNotification。

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

,並在選擇獲取鍵盤框架:

- (void)keyboardWillShow:(NSNotification *)iNotification { 
    NSDictionary *userInfo = [iNotification userInfo]; 
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; 
    CGRect keyboardRect = [aValue CGRectValue]; 
} 
+0

知道了!但我想知道我是否在UITextField上設置了框架,我怎樣才能設置每次?代表 –

4

我面臨這個問題,通過使用鍵盤上的通知觀察者解決。

//set observer in textFieldShouldBeginEditing like  
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationMethod:) name:UIKeyboardWillChangeFrameNotification object:nil]; 
    return YES; 
} 

// method implementation 
- (void)myNotificationMethod:(NSNotification*)notification 
{ 
    NSDictionary* keyboardInfo = [notification userInfo]; 
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey]; 
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue]; 
    NSLog(@"%@",keyboardFrameBegin); 

    NSLog(@"%f",keyboardFrameBeginRect.size.height); 
} 

//remove observer 
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ 
    [[NSNotificationCenter defaultCenter ]removeObserver:self];  
    return YES; 
} 
+0

非常感謝,我想我完成了我的問題:) –