动态获取键盘的框架

时间:2012-08-16 14:25:25

标签: iphone ios keyboard uitextview

是否可以动态获取键盘的框架,实际上是它的高度?因为我有UITextView并且我想根据键盘框高度调整其高度,当键盘的输入方法改变时。如您所知,不同的输入法可能会有不同的键盘框架高度。

4 个答案:

答案 0 :(得分:101)

试试这个:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWasShown:)
                                         name:UIKeyboardDidShowNotification
                                       object:nil];

- (void)keyboardWasShown:(NSNotification *)notification
{

// Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

//Given size may not account for screen rotation
int height = MIN(keyboardSize.height,keyboardSize.width);
int width = MAX(keyboardSize.height,keyboardSize.width);

//your other code here..........
}

Tutorial for more information

答案 1 :(得分:7)

只需按照Apple的本教程,您就会得到您想要的内容。 Apple Documentation。要确定键盘覆盖的区域,请参阅此tutorial

答案 2 :(得分:2)

对于Swift 3用户,@ Hector代码(带有一些补充)将是:

viewDidLoad添加观察者:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil)

然后实现这些方法:

func keyboardDidShow(_ notification: NSNotification) {
     print("Keyboard will show!")
     // print(notification.userInfo)

     let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size
     print("Keyboard size: \(keyboardSize)")  

     let height = min(keyboardSize.height, keyboardSize.width)
     let width = max(keyboardSize.height, keyboardSize.width)

}

func keyboardDidHide(_ notification: NSNotification) {
        print("Keyboard will hide!")
}

答案 3 :(得分:0)

您可以将此代码添加到包含Swift 3中文本字段的视图中。这将使文本字段使用键盘上下动画。

register_setting( 'pf404', 'pf404_options', 'sanitize_function' );

function sanitize_function($input){

    myclass::load_api_data($input['pf404_field_apikey'], $input['pf404_field_animal']);         
    return $input;
}