xcode UIView backgroundColor 颜色循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6241655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIView backgroundColor color cycle
提问by MaleBuffy
First of all, I am new to this Xcode/Objective-C thing, so go easy on me! :) I made a test app that, by pressing some buttons, the background changes. I have a red, blue, green, white, black and revive button.
首先,我是这个 Xcode/Objective-C 的新手,所以放轻松!:) 我制作了一个测试应用程序,通过按下一些按钮,背景会发生变化。我有一个红色、蓝色、绿色、白色、黑色和复活按钮。
I made the app change the color of the backgrnd by pressing all the color buttons. However, I want to make the app cycle through the colors, say 100 times very fast when pressing the Revive button. For some reason, it doesnt work.
我让应用程序通过按下所有颜色按钮来更改背景的颜色。但是,我想让应用程序在颜色之间循环,例如在按下 Revive 按钮时非常快地循环 100 次。由于某种原因,它不起作用。
The following is the code that isn't working:
以下是不起作用的代码:
Using the code below, only changes to the last color.
使用下面的代码,只更改最后一种颜色。
- (IBAction)Revive:(id)sender {
for (int y=0; y < 100; y++) {
view1.backgroundColor = [UIColor redColor];
view1.backgroundColor = [UIColor greenColor];
view1.backgroundColor = [UIColor blueColor];
view1.backgroundColor = [UIColor whiteColor];
view1.backgroundColor = [UIColor blackColor];
}
}
Using the code below, whitout the loop, the app fades from white to black
使用下面的代码,没有循环,应用程序从白色淡入黑色
- (IBAction)Revive:(id)sender {
[UIView animateWithDuration:0.2 animations:^{
view1.backgroundColor = [UIColor redColor];
view1.backgroundColor = [UIColor greenColor];
view1.backgroundColor = [UIColor blueColor];
view1.backgroundColor = [UIColor whiteColor];
view1.backgroundColor = [UIColor blackColor];
}];
[UIView commitAnimations];
}
Anyone knows why this is happening and a solution to my problem?
任何人都知道为什么会发生这种情况以及我的问题的解决方案?
回答by Jacob Relkin
This will work:
这将起作用:
- (void) doBackgroundColorAnimation {
static NSInteger i = 0;
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor whiteColor], [UIColor blackColor], nil];
if(i >= [colors count]) {
i = 0;
}
[UIView animateWithDuration:2.0f animations:^{
self.view.backgroundColor = [colors objectAtIndex:i];
} completion:^(BOOL finished) {
++i;
[self doBackgroundColorAnimation];
}];
}
回答by Antwan van Houdt
The view needs time to redraw, in the first example you have you set the backgroundcolor, but the view doesn't redraw untill you are done with that method. With the animation its the same thing, its like saying the following:
视图需要时间来重绘,在第一个示例中,您设置了背景色,但是在您完成该方法之前,视图不会重绘。动画是同样的事情,就像在说以下内容:
int x = 0;
x = 5;
x = 6;
// why is x 6 ? :(
I would use an NSTimer to loop through the colors.
我会使用 NSTimer 来循环颜色。