2011-10-25 44 views
0

我使用下面的代碼,以創建一個UIScrollView更改視圖中的UIScrollView用的NSTimer

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
scroll.pagingEnabled = YES; 
NSInteger numberOfViews = 3; 
for (int i = 0; i < numberOfViews; i++) { 

    CGFloat yOrigin = i * self.view.frame.size.width; 
    UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
    awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1]; 
    [scroll addSubview:awesomeView]; 

} 

scroll.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height); 

[self.view addSubview:scroll]; 

的問題是:如何實現以更改頁面每4秒NSTimer

[NSTimer scheduledTimerWithTimeInterval:4.0f 
           target:self 
           selector:@selector(updateCounter:) 
           userInfo:nil 
           repeats:YES]; 

我在努力編寫updateCounter方法。請幫助

- (void)updateCounter:(NSTimer *)theTimer { 
NSInteger numberOfViews = 3; 
    int i = 0; i++; 
    if (i < numberOfViews) { 

    yOrigin = i * self.view.frame.size.width; 
    [scroll scrollRectToVisible:CGRectMake(yOrigin, 0, self.view.frame.size.width,  self.view.frame.size.height) animated:YES]; 
} 

return; } 

OK,所以這段代碼,從視圖1圖2NSTimer的變化,但它停止,它在接下來的4秒後不會更改爲圖3。我想要做的是從查看1查看 2,4秒後,再到查看3,4秒後等等。我想擁有儘可能多的視圖,因爲我需要。

+0

我認爲它是因爲每次調用updateCounter時都會重新初始化i(i = 0)。嘗試讓計數器成爲實例變量,並在我超出頁面數時重置/倒計數。 – chourobin

+0

糟糕,你不應該有updateCount內的循環。定時器每4秒發射一次就是你的循環。 – chourobin

回答

0

你是對所做的一切。現在您需要實現updateCounter,以便scrollView的滾動自動發生。維護全局寬度計數器。請在每次致電updateCounter時更新此計數器。你可以這樣做 -

int global_width = self.view.frame.size.width; 
int global_height = self.view.frame.size.height; 
- (void) updateCounter 
{ 
    int width = (global_width%self.view.frame.size.width)*self.view.frame.size.width; 
    [yourScrollView scrollRectToVisible:CGRectMake(0, 0, width, global_height) animated:YES]; 

    global_width += self.view.frame.size.width; 
    return; 
} 

這樣你就可以在頁面之間自動循環。好的這個工作,所有這些都是徒手輸入的。但是這個概念是正確的。

+0

好的,所以我修改了我的問題。正如你在上一部分中看到的,我更改了updateCounter方法,它從視圖1變爲視圖2,但隨後停止,我如何在接下來的4秒後更改視圖3?謝謝 – naSh

0

如果你想更新計數器每四秒,請致電updateCounter方法是這樣的:

[NSTimer scheduledTimerWithTimeInterval:4.0f 
           target:self 
           selector:@selector(updateCounter) 
           userInfo:nil 
           repeats:YES]; 

在有你做了什麼是兩點不同。 #1,時間間隔是4秒。 #2,如果沒有任何參數進入updateCounter方法,請不要在選擇器中附加冒號。

然後你updateCounter方法:

- (void) updateCounter 
{ 
    // what view are you modifying? 
    // the content view or a subview within the ScrollView's contentView ? 
} 
+0

我目前有3個視圖,因此我想用updateCounter更改每個視圖。因此,如果我在updateCounter方法中添加以下內容:static int count = 0; count ++;開關(count&3){case 1:break;情況2:休息;情況3:休息; }}我想在每種情況下添加圖像和聲音。接下來的問題是:我如何在每種情況下編寫這個計數器,以更新當前視圖和每個3個視圖的視圖。 – naSh