0

情况:我有一个位于视图顶部的各种工具栏(不是 UIToolbar,只是自定义 UIView)。该工具栏有许多按钮。在它的正下方,我有一个带有表单的滚动视图。当点击工具栏上的按钮时,相应的表单应该从右侧或左侧动画到屏幕上,具体取决于点击哪个按钮。我不希望工具栏继续前进。但是,当用户在滚动视图上向上或向下滚动时,我确实希望工具栏向上滚动。我现在完成它的方式是在 scrollViewDidScroll 委托方法中(注意,如果它是通过按下工具栏上的按钮,我只允许水平滚动):

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.x != 0 && _shouldScrollHorizontally == NO)
    {
        CGPoint offset = scrollView.contentOffset;
        offset.x = 0;
        scrollView.contentOffset = offset;
    }

    CGRect buttonFrame = [_buttons frame];

    buttonFrame.origin.y = -scrollView.contentOffset.y + 10;

    [_buttons setFrame:buttonFrame];
}

但是,我担心这效率低下并且会导致一些延迟。我想知道是否有更好的方法来完成我想要实现的目标。

归根结底,如果滚动视图水平滚动,我希望工具栏保持静止,但如果滚动视图垂直滚动,我希望工具栏与滚动视图一起移动。

感谢您的任何建议!

4

1 回答 1

1

由于仅在点击按钮时才允许水平“滚动”,因此将UIScrollView contentSize宽度设置为屏幕的宽度和适当的高度。对于点击按钮时水平“滚动”,只需动画水平移动视图。

视图层次结构类似于outerViewUIScrollView contentSize当前设置的宽度和高度。您的滚动视图是 的子视图,outerView工具栏是滚动视图的子视图。

要为水平运动设置动画,通常最简单的方法是更改outerView.center ​​ 和toolbarView.center,例如:

CGPoint newCenterPoint;
CGPoint newToolbarCenterPoint;

CGPoint centerPoint1 = // set center as appropriate
CGPoint centerPoint2 = // set center as appropriate
CGPoint centerPoint3 = // set center as appropriate

CGPoint toolbarCenter1 = // set center as appropriate
CGPoint toolbarCenter2 = // set center as appropriate
CGPoint toolbarCenter3 = // set center as appropriate

if (buttonTapped == button1) {
    newCenterPoint = centerPoint1;
    newToolbarCenterPoint = toolbarCenter1;
} else if (buttonTapped == button2){
    newCenterPoint = centerPoint2;
    newToolbarCenterPoint = toolbarCenter2;
} else if (buttonTapped == button3){
    newCenterPoint = centerPoint3;
    newToolbarCenterPoint = toolbarCenter3;
}
[UIView animateWithDuration:0.25 animations:^{
    outerView.center = newCenterPoint;
    toolbarView.center = newToolbarCenterPoint;
}];
于 2013-07-06T12:06:28.720 回答