簡體   English   中英

iPhone:如何在視圖中隨機播放按鈕

[英]iPhone:How can I shuffle buttons in view

我有很多沒有。 上的按鈕,並且我想隨機播放按鈕(位置變化),然后如何在視圖中隨機播放按鈕。

你可以這樣做

  1. 用一組CGPoint創建一個數組,您需要將這些點存儲為字符串。
  2. 在layoutSubViews方法中,設置如下所示:

      -(void)layoutSubViews{ [self.subviews enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) { CGPoint newPoint = CGPointFromString([positionsArray objectAtIndex:idx]); object.frame = CGRectMake(newPoint.x,newPoint.y,object.frame.size.width,object.frame.size.height); }]; 

    }

  3. 然后您將需要對位置數組中的位置進行混洗,您可以在此處看到示例方法: 如何對數組進行混洗

  4. 現在,每次您需要調整位置時,都可以在視圖上調用-(void)setNeedsLayout

還有更多選擇,但這是我想到的第一個。

祝好運

使用arc4random()

並更改按鈕的位置

在您的.h fileUIButton *buttonsarray[10];

在您的.m file

  // Make array of button using following way.I used this method to creates button and you can use yours.
 - (void)viewDidLoad {
     [super viewDidLoad];

      float y = 5;
      int x = 0;
      int count = 0;
      for (int i = 0 ; i < 10; i++)
     {
        count ++;
        buttonsarray[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        buttonsarray[i].frame =  CGRectMake(x, y, 100, 100);
       [buttonsarray[i] setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
         x = x + 105;
        [self.view addSubview:b[i]];
        if(count == 3)
       {
        count = 0;
        x = 0;
        y = y+ 105;
      }


    }
}


  // This function will soufflé your buttons
 - (IBAction)btnClicked:(id)sender
   {
     int n = 10;
     int swaper;
     for (int i = 0 ; i < 10 ; i++)
     {
       int r = arc4random()%n;
       if(r != swaper){
        swaper = r;
        CGRect r1 = buttonsarray[i].frame;      
        buttonsarray[i].frame = buttonsarray[swaper].frame;
        buttonsarray[swaper].frame = r1; 

        n--;
    }

  }
}

希望這個能對您有所幫助..

暫無
暫無

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

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