簡體   English   中英

按下UIButton時的隨機值

[英]Random value when UIButton pressed

我希望能夠在按下UIButton時隨機分配一個值。

我嘗試了if else語句,但它似乎崩潰了。

每次您按下按鈕時,都會生成一個隨機數並將其輸出到控制台。

- (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());
}

將IBAction添加到您的按鈕,然后執行以下操作:

- (IBAction)buttonPress:(id)sender
{
    myValue = arc4random() % MAX_VALUE;
}

這將從[0,MAX_VALUE)生成一個隨機數,並將其存儲在(int)變量myValue

嘗試這個:

[ButtonName addTarget:self action:@selector(randomize) forControlEvents:UIControlEventTouchUpInside];

- (void) randomize
{

    random = arc4random()%5;

    switch (random)
    {
        case 0:
                *condition*
             break;
        case 1:
                *condition*
             break;

.....

}

希望對您有幫助。

暫無
暫無

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

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