无限滚动背景(UIView动画)

时间:2014-05-15 15:23:57

标签: xcode animation uiview

我正试图通过让两个UIViews滚动并像传送带一样互相替换来实现无限滚动的背景。这是我的代码到目前为止,我似乎无法让它工作

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    bg1 = [[UIView alloc] initWithFrame:self.view.frame];
    [bg1 setBackgroundColor:[UIColor redColor]];
    bg2 = [[UIView alloc] initWithFrame:self.view.frame];
    [bg2 setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:bg1];
    [self.view addSubview:bg2];
    [self.view bringSubviewToFront:bg1];
    [self animate];
}

- (void)animate {
    [UIView animateWithDuration:3000 animations:^{
        bg1.frame = CGRectOffset(bg1.frame, 0, bg1.frame.size.height);
    }completion:^(BOOL done) {
        if (done) {
            bg1.frame = CGRectOffset(bg1.frame, 0, -bg1.frame.size.height);
            [self.view sendSubviewToBack:bg1];
            [UIView animateWithDuration:3000 animations:^{
                bg2.frame = CGRectOffset(bg2.frame, 0, bg2.frame.size.height);
            }completion:^(BOOL done) {
                if (done) {
                    bg2.frame = CGRectOffset(bg2.frame, 0, -bg2.frame.size.height);
                    [self.view sendSubviewToBack:bg2];
                    [self animate];
                }
            }];
        }
    }];
}

1 个答案:

答案 0 :(得分:2)

我的坏!我以为withDuration是在ms。这是几秒钟!

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    bg1 = [[UIView alloc] initWithFrame:self.view.frame];
    [bg1 setBackgroundColor:[UIColor redColor]];
    bg2 = [[UIView alloc] initWithFrame:self.view.frame];
    [bg2 setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:bg1];
    [self.view addSubview:bg2];
    [self.view bringSubviewToFront:bg1];
    [self animate];
}

- (void)animate {
    [UIView animateWithDuration:3 animations:^{
        bg1.frame = CGRectOffset(bg1.frame, 0, bg1.frame.size.height);
    }completion:^(BOOL done) {
        if (done) {
            bg1.frame = CGRectOffset(bg1.frame, 0, -bg1.frame.size.height);
            [self.view sendSubviewToBack:bg1];
            [UIView animateWithDuration:3 animations:^{
                bg2.frame = CGRectOffset(bg2.frame, 0, bg2.frame.size.height);
            }completion:^(BOOL done) {
                if (done) {
                    bg2.frame = CGRectOffset(bg2.frame, 0, -bg2.frame.size.height);
                    [self.view sendSubviewToBack:bg2];
                    [self animate];
                }
            }];
        }
    }];
}