2011-11-18 38 views
3

在我的UIView中,我有一個UIScrollView,它填充第一個視圖,所以當內容大於iPhone屏幕大小時,用戶可以向下滾動頁面。它運行良好,但是當用戶完成滾動移動時(即移除他的手指),頁面會回到原始位置。顯然這不是我想要的,怎麼可以避免?用戶完成滾動後,UIScrollView不會保留在原位

這裏是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; 
} 

另外一個問題是:怎麼可能讓它使得用戶只能向下滾動,那就是看到的內容中,其中有拿出來看的底部,而不是向上,以便滾動內容開始之前有空間。在

+0

我也有這個問題,還沒有找到滿意的答案。認爲它比其他任何東西都更多。 – jbat100

+0

我可以回答您的其他問題,但您應該將其作爲單獨問題提出。以這樣的方式提問並不能幫助將來的訪問者解決這個問題。 – Aberrant

+1

還有一件事,你應該把你的初始化代碼放在說「//初始​​化代碼」的地方。 ;) – Aberrant

回答

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]; 
1

基本上你只需要根據內容設置你的滾動視圖的contentSize。

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