[英]Random value when UIButton pressed
I want to be able to random a value when a UIButton is pressed. 我希望能够在按下UIButton时随机分配一个值。
I tried if else statement but it seems to be crashing. 我尝试了if else语句,但它似乎崩溃了。
This will generate and output a random number to the console everytime you press the button. 每次您按下按钮时,都会生成一个随机数并将其输出到控制台。
- (void)viewDidLoad
{
UIButton *button = [UIButton buttonWithStyle:UIButtonStyleRoundedRect];
[button addTarget:self withAction:@selector(random) forEvent:UIControlEventTouchUpInside];
[button setFrame:CGRect(50,50,100,50);
[self.view addsubview:button];
}
- (void)random
{
NSLog(@"%i",arc4random());
}
Add an IBAction to your button, and do this: 将IBAction添加到您的按钮,然后执行以下操作:
- (IBAction)buttonPress:(id)sender
{
myValue = arc4random() % MAX_VALUE;
}
This will generate a random number from [0, MAX_VALUE), and store it in the (int) variable myValue
. 这将从[0,MAX_VALUE)生成一个随机数,并将其存储在(int)变量myValue
。
Try this: 尝试这个:
[ButtonName addTarget:self action:@selector(randomize) forControlEvents:UIControlEventTouchUpInside];
- (void) randomize
{
random = arc4random()%5;
switch (random)
{
case 0:
*condition*
break;
case 1:
*condition*
break;
.....
}
hope this could help you. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.