簡體   English   中英

從for循環中更改背景顏色? [ios]

[英]Changing background color from within for loop? [ios]

我試圖通過遍歷每個對應於一種顏色的數值列表來更改背景顏色。 對於列表中的每個整數,我希望背景更改為該顏色,暫停一秒鍾,然后更改為列表中的下一個顏色。 但是,即使遍歷整個列表,背景色似乎也只會更改為列表末尾的顏色。 我可以做些什么,以便更改列表中每個項目的背景?

當用戶按下播放按鈕時,將執行以下代碼:

- (IBAction)play:(id)sender {
    [self.mem addObject: [NSNumber numberWithInt: arc4random() % 3]];

    [UIView animateWithDuration:.5 delay:.5 options:UIViewAnimationOptionTransitionFlipFromRight
                 animations:
     ^(void) {
         for (int i = 0; i < [self.mem count]; i++) {
             if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:0]) {
                 self.view.backgroundColor = [UIColor blueColor];
             } else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:1]) {
                 self.view.backgroundColor = [UIColor greenColor];
             } else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:2]) {
                 self.view.backgroundColor = [UIColor redColor];
             } else {
                 self.view.backgroundColor = [UIColor cyanColor];
             }
         }
     }
                     completion:
     ^(BOOL finished) {
         if(finished){
         }
     }];
}

任何幫助表示贊賞,謝謝!

-animateWithDuration:options:animations:將使用您在動畫塊中最后設置的任何值來執行動畫-不會在您進行的每次更改上花費duration秒數。

如果要設置從一種顏色到另一種顏色再到另一種顏色的背景動畫,則需要分步進行。 使用完成塊來觸發另一個更改(可能只是再次調用-play: 您可能需要在ivar中保存一些狀態,以使其更容易知道顏色順序。

你很親密! 我已經更新了您的方法,您應該能夠簡單地復制並粘貼它。有關說明,請參見@Caleb的答案。

-(IBAction)play:(id)sender {
    static UIColor *color;
    // i is the ivar that saves the state in the color sequence
    static int i = 0;

    if (sender) {
        i = 0;
        [self.mem addObject:[NSNumber numberWithInt: arc4random() % 3]];
    }

    if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:0]) {
        color = [UIColor blueColor];
    } else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:1]) {
        color = [UIColor greenColor];
    } else if ([self.mem objectAtIndex:i] == [NSNumber numberWithInt:2]) {
        color = [UIColor redColor];
    } else {
        color = [UIColor cyanColor];
    }

    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
        self.backgroundColor = color;
    } completion:^(BOOL finished) {
        // Only continue animating if the play button has not been pressed
        if (i < self.mem.count - 1) {
            i += 1;
            // trigger another change by calling play:
            [self play:nil];
        }
    }];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM