用户完成滚动后,UIScrollView将不会保留在原位

时间:2011-11-18 09:11:56

标签: ios

在我的UIView中,我有一个UIScrollView填充第一个视图,因此当内容大于iPhone屏幕大小时,用户可以向下滚动页面。它运作良好,但是当用户完成滚动运动 - 即移开他的手指时,页面会快速回到原始位置。显然这不是我想要的,怎么可以避免?

以下是UIView类中的相关代码,它声明并使用UIScrollView类。

@implementation TestView


- (id)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
    }

    CGRect scrollViewFrame = CGRectMake(0, 0, 320, 460);
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:scrollViewFrame];
    scrollView.canCancelContentTouches=NO;
    [self addSubview:scrollView];

    CGSize scrollViewContentSize = CGSizeMake(320, 500);
    [scrollView setContentSize:scrollViewContentSize];

    CGRect rectForBigRedSquare = CGRectMake(50, 50, 200, 200);
    UILabel *redSquare = [[UILabel alloc] initWithFrame:rectForBigRedSquare];
    [redSquare setBackgroundColor:[UIColor redColor]];

    [scrollView addSubview:redSquare];
    return self;
}

另一个问题是:如何才能使用户只能向下滚动,即查看底部不在视野范围内的内容,而不是向上滚动以便之前有空格内容的开始。在

3 个答案:

答案 0 :(得分:1)

基本上你只需要根据内容设置你的scrollview的contentSize。

CGSize scrollViewSize = CGSizeMake(newWidth, newHeight);
[self.myScrollView setContentSize:scrollViewSize];

答案 1 :(得分:0)

好的,让这个滚动视图正常工作的最简单方法是确保滚动视图 的内容大小与您希望的内容的帧大小相同 滚动。

您可以通过将内容视图添加到其中以添加您希望显示的所有视图,然后将该内容视图添加到滚动视图,同时确保将scrollview的内容大小设置为内容视图的帧大小来实现此目的

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];

    UIView* contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1280, 460)];

    UIView* redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [redView setBackgroundColor:[UIColor redColor]];
    [contentView addSubview:redView];
    [redView release];

    UIView* blueView = [[UIView alloc] initWithFrame:CGRectMake(960, 0, 320, 460)];
    [redView setBackgroundColor:[UIColor blueColor]];
    [contentView addSubview:blueView];
    [blueView release];

    CGSize contentViewSize = contentView.frame.size;
    [scrollView addSubview:contentView];
    [scrollView setContentSize:contentViewSize];
    [contentView release];

    [self addSubview:scrollView];

答案 2 :(得分:0)

我正在使用的应用程序具有类似的症状。用户可以向下滚动,但在释放时,视图将捕捉回到初始位置。页面设置如下:

[VIEW] [SAFE AREA] [SCROLL VIEW] [CONTENT VIEW]

我强烈怀疑由几次调整迭代引起的自动版式和手动约束的结合会导致此问题。要解决此问题,请从视图中删除所有约束。

为滚动视图分配了以下约束:

Scroll View.leading = Safe Area.leading
Scroll View.top     = Safe Area.top
Scroll View.trailing= Safe Area.trailing
Scroll View.bottom  = Safe Area.bottom

然后为内容视图分配了以下约束

ContentView.Leading = Scroll View.Leading
ContentView.top     = Scroll View.top
ContentView.centerX = ScrollView.centerX

内容视图还具有以下自我约束条件

height = 1000