我知道如何做一个全局变量,但是每当我尝试用随机数函数定义一个全局变量时,xcode 都会说“初始化元素不是常量”。编译器不想从随机数中生成变量,因为随机数函数不是常数。
如何生成一个随机数,然后将相同的值用于多个操作?(例如,定义一种颜色,然后将该值写入标签?)
代码:
#import "Slider_with_IBAppDelegate.h"
float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^this is where I get the error: "initializer element is not constant"
@synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:@"%f", hue];
}
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}
- - 编辑 - - -
感谢您的建议。但是,它仍然对我不起作用,我做错了什么?
新代码:
#import "Slider_with_IBAppDelegate.h"
float const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^I still get the error: "initializer element is not constant."
@synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:@"%f", hue];
}
//^this is where I get the error "'hue' undeclared (first use of this function)"
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
hue = ((arc4random() % ((unsigned)1000 + 1))/1000.0);
/*here I get the error "assignment of read-only variable 'hue.'"
If I insert "float" just before hue, I do not get this error,
but it still won't compile because of the error above.*/
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}