对于iPhone界面控件的操作应该算是开发中必备的能力。键盘出现的时候上移相关的控件算是常见的需求,但是从这么多人问这个问题就可以看出,还是有很多人对这些需求的实现方式有疑问。
对于这个问题,主要是通过增加对键盘出现和消失的相应的Notification,然后在键盘出现和消息的时候,通过设置相关控件的frame来实现。相关代码如下,来源自stackoverflow。
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if ([sender isEqual:_textField])
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
}
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)notif
{
//keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
if ([_textField isFirstResponder] && self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (![_textField isFirstResponder] && self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
- (void)viewWillAppear:(BOOL)animated
{
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:self.view.window];
}
- (void)viewWillDisappear:(BOOL)animated
{
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
本文介绍了一种常见需求的实现方法:当iPhone键盘弹出时,如何通过监听Notification并调整视图的位置和大小来确保输入框不会被遮挡。提供了一个具体的代码示例,演示了如何使用Swift或Objective-C进行实现。
2584

被折叠的 条评论
为什么被折叠?



