滚动视图突出显示?

时间:2012-02-28 13:03:32

标签: iphone objective-c ipad

我正在尝试使用键盘顶部的下一个按钮滚动视图中的textarea字段,当它切换到最后一个textarea字段时,它向下滚动并隐藏在键盘后面。

代码:

 (CGRect)getObjectRectFromRoot {

    int yOffset = 0;

   yOffset += self.view.frame.origin.y;

   UIView* suView = self.view.superview;

    while (suView) {
       yOffset += suView.frame.origin.y;
        suView = suView.superview;
    }

    CGRect r;
    r.size.width = 700;
    r.size.height = 700;
    r.size.width = self.view.frame.size.width;
    r.size.height = self.view.frame.size.height;
    r.origin.x = 0;
    r.origin.y = yOffset;

    return r;

}

1 个答案:

答案 0 :(得分:0)

在textField的两个委托方法中实现此代码将执行您想要的操作。这是 textFieldDidBeginEditing

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect textFieldRect =
[self.view.window convertRect:textField.bounds fromView:textField];
CGRect viewRect =
[self.view.window convertRect:self.view.bounds fromView:self.view];

CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator =
midline - viewRect.origin.y
- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator =
(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
* viewRect.size.height;
CGFloat heightFraction = numerator / denominator;

if (heightFraction < 0.0)
{
    heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
    heightFraction = 1.0;
}

UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait ||
    orientation == UIInterfaceOrientationPortraitUpsideDown)
{
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
    animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}

CGRect viewFrame = self.view.frame;
viewFrame.origin.y -= animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];

[UIView commitAnimations];
}

这是 textFieldDidEndEditing:

- (void)textFieldDidEndEditing:(UITextField *)textField
{
CGRect viewFrame = self.view.frame;
viewFrame.origin.y += animatedDistance;

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

[self.view setFrame:viewFrame];
[self textFieldShouldReturn:textField];

[UIView commitAnimations];

}

如果您想要按钮,可以使用上面的代码设置 IBAction

代码也可以与您想要的任何其他类型的操作或视图一起使用!