当 iPad 虚拟键盘出现时,它覆盖了我的视图中的一些文本字段。有没有办法在键盘出现时将 ViewController 向上移动?
问问题
4023 次
3 回答
7
我已经为我的一个应用程序编写了这段代码。
它会自动检测 TextField 的位置并相应地滚动 baseView。
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField:textField up:NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
CGPoint temp = [textField.superview convertPoint:textField.frame.origin toView:nil];
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait){
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 264-(1024-moveUpValue-5);
}
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
if(up) {
int moveUpValue = 1004-temp.y+textField.frame.size.height;
animatedDis = 264-(1004-moveUpValue-5);
}
}
else if(orientation == UIInterfaceOrientationLandscapeLeft) {
if(up) {
int moveUpValue = temp.x+textField.frame.size.height;
animatedDis = 352-(768-moveUpValue-5);
}
}
else
{
if(up) {
int moveUpValue = 768-temp.x+textField.frame.size.height;
animatedDis = 352-(768-moveUpValue-5);
}
}
if(animatedDis>0)
{
const int movementDistance = animatedDis;
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
if (orientation == UIInterfaceOrientationPortrait){
baseViewController.view.frame = CGRectOffset(baseViewController.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
baseViewController.view.frame = CGRectOffset(baseViewController.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationLandscapeLeft) {
baseViewController.view.frame = CGRectOffset(baseViewController.view.frame, 0, movement);
}
else {
baseViewController.view.frame = CGRectOffset(baseViewController.view.frame, 0, movement);
}
[UIView commitAnimations];
}
}
于 2011-05-04T03:51:59.120 回答
1
我的建议是将你的对象放在一个 上UIScrollView
,然后当键盘出现时,你就可以使用scrollRectToVisible:
.
[scroller scrollRectToVisible:frame animated:YES];
于 2011-01-14T03:05:57.497 回答
1
当 up = NO 时,请务必将 ValayPatel 代码“if”语句更改if(animatedDis>0 || !up)
为 for 条件,否则移动的视图始终位于先前位置。
于 2013-03-18T03:58:15.793 回答