首先就是获取键盘的尺寸,需要手动调用 registerForKeyboardNotifications 方法,其他两个会自动调用,弹出的键盘高 216(输入英文时候),
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self registerForKeyboardNotifications];
UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
[self.view addSubview:tv];
[tv release];
}
- (void) registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
- (void) keyboardWasShown:(NSNotification *) notif
{
NSDictionary *info = [notif userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
NSLog(@"keyBoard:%f", keyboardSize.height); //216
///keyboardWasShown = YES;
}
- (void) keyboardWasHidden:(NSNotification *) notif
{
NSDictionary *info = [notif userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
// keyboardWasShown = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
//增加监听,当键盘出现或改变时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//增加监听,当键退出时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
}
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)]; [topView setBarStyle:UIBarStyleBlackTranslucent]; UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(2, 5, 50, 25); [btn addTarget:self action:@selector(dismissKeyBoard) forControlEvents:UIControlEventTouchUpInside]; [btn setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal]; UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithCustomView:btn]; NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil]; [topView setItems:buttonsArray]; [textfield setInputAccessoryView:topView]; -(void)dismissKeyBoard { [textfield resignFirstResponder]; }