您的位置:首页 > 产品设计 > UI/UE

<转>对UITextField的键盘处理方法

2012-09-21 19:19 330 查看
http://blog.csdn.ofcdn.net/ch_soft/article/details/6948119

- (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*)aNotification

{

//如果键盘是显示状态,不用做重复的操作

if (keyboardShown)

return;

//获得键盘通知的用户信息字典

NSDictionary* info = [aNotification userInfo];

// 取得键盘尺寸.

NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];

CGSize keyboardSize = [aValue CGRectValue].size;

// 重新设置scrollView的size

CGRect viewFrame = [myScrollView frame];

viewFrame.size.height -= keyboardSize.height;

myScrollView.frame = viewFrame;

// 把当前被挡住的text field滚动到view中适当的可见位置.

CGRect textFieldRect = [activeField frame];

[myScrollView scrollRectToVisible:textFieldRect animated:YES];

//记录当前textField的偏移量,方便隐藏键盘时,恢复textField到原来位置

oldContentOffsetValue = [myScrollView contentOffset].y;

//计算textField滚动到的适当位置

CGFloat value = (activeField.frame.origin.y+myScrollView.frame.origin.y+activeField.frame.size.height - self.view.frame.size.height + keyboardSize.height)+2.0f;

//value>0则表示需要滚动,小于0表示当前textField没有被挡住,不需要滚动

if (value > 0) {

//使textField滚动到适当位置

[myScrollView setContentOffset:CGPointMake(0, value) animated:YES];

isNeedSetOffset = YES;//更改状态标志为需要滚动

}

//更改键盘状态标志为已显示

keyboardShown = YES;

}

// 键盘隐藏时调用此方法

- (void)keyboardWasHidden:(NSNotification*)aNotification

{

NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.

NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];

CGSize keyboardSize = [aValue CGRectValue].size;

// Reset the height of the scroll view to its original value

CGRect viewFrame = [myScrollView frame];

viewFrame.size.height += keyboardSize.height;

myScrollView.frame = viewFrame;

//如果状态标志为需要滚动,则要执行textFiled复位操作

if (isNeedSetOffset) {

//oldContentOffsetValue记录了textField原来的位置,复位即可

[myScrollView setContentOffset:CGPointMake(0, oldContentOffsetValue) animated:YES];

}

//复位状态标志

isNeedSetOffset = NO;

keyboardShown = NO;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐