使用NSTimer在UIScrollView中更改视图

时间:2011-10-25 01:38:40

标签: ios uiview uiscrollview nstimer

我使用以下代码创建UIScrollView

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

问题是:如何实施NSTimer以便每4秒更改一次页面?

    [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; }

好的,所以使用此代码,NSTimer视图1 更改为视图2 ,但它会停止,在接下来的4秒后不会更改到查看3 。我想要做的是在4秒后从 view 1 更改为 view 2,然后在4秒后更改为 view 3 ,等等。我想拥有尽可能多的观点。

2 个答案:

答案 0 :(得分: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 ?   
}

答案 1 :(得分: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;
}

这样您就可以自动在页面之间循环。 Hoep这是有效的,所有这些都是徒手打字。但这个概念是正确的。