刚开始的时候,非常害怕有输入框的界面,因为键盘出现后,用掉了大部分的屏幕,很多输入框都被覆盖了。随着经验的增加,突然有一天想明白了,其实很简单。
下面是其方法:
1,把所有空间放到一个UIScrollView之中,而不是缺省的UIView
一般情况下,把UIScrollView设成100%覆盖UIView。
其它空间,如UILabel, UITextField, UIButton等可以使用大小自动调整等。
下面是本人APP - 多彩旅行的登陆界面:
2, 处理键盘显示、隐藏时调整ScrollView的ContentSize
第一步:view出现后开始侦听键盘显示、隐藏时间。
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
。。。
NSNotificationCenter *nCenter = [NSNotificationCenter defaultCenter];
[nCenter addObserver:self
selector:@selector(keyboardDidShown:)
name:UIKeyboardDidShowNotification object:nil];
[nCenter addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
}
第二步:view消失时注销键盘侦听。
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
。。。
NSNotificationCenter *nCenter = [NSNotificationCenter defaultCenter];
[nCenter removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[nCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
第三步:键盘显示事件处理。
- (void)keyboardDidShown:(NSNotification *)notification
{
NSDictionary* info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// 找到合理的键盘高度
if (kbSize.width < kbSize.height) {
CGFloat t = kbSize.height;
kbSize.height = kbSize.width;
kbSize.width = t;
}
// UIView的大小
CGSize vwSize = self.view.bounds.size;
// 最低高度=最下面控件(这里是txtRegister)的起始位置(origin.y)+高度(size.height)
CGFloat minBottom = txtRegister.frame.origin.y + txtRegister.frame.size.height * 2;
// 最低高度加上键盘的高度
minBottom += kbSize.height;
// 如果键盘没有覆盖最下面的控件,则最低高度等于窗口大小
if (vwSize.height > minBottom)
minBottom = vwSize.height;
// 调整ScrollView的ContentSize等于最低高度(宽度不变)
// 这样所有控件都可以移动到键盘之外
self.viewScroll.contentSize = CGSizeMake(vwSize.width, minBottom);
}
第四步:键盘消失事件处理。
- (void)keyboardWillHide:(NSNotification *)notification
{
CGSize vwSize = self.view.bounds.size;
CGFloat minBottom = txtRegister.frame.origin.y + txtRegister.frame.size.height * 2;
if (vwSize.height > minBottom)
minBottom = vwSize.height;
self.viewScroll.contentSize = CGSizeMake(vwSize.width, minBottom);
}
希望对大家有所帮助。