1

我有很多没有。我的视图上的按钮,我想洗牌按钮(改变位置)那么我怎样才能洗牌我的视图中的按钮。

4

2 回答 2

0

你可以这样做

  1. 使用一组 CGPoints 创建一个数组,您需要将这些点存储为字符串。
  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. 然后你需要洗牌位置数组中的位置,你可以在这里看到一个示例方法:How to Shuffle an Array

  4. 现在,每次您需要洗牌时,您都可以-(void)setNeedsLayout在视图上调用。

还有更多选择,但这是我首先想到的。

祝你好运

于 2012-05-09T05:12:53.860 回答
0

采用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--;
    }

  }
}

希望对你有帮助..

于 2012-05-09T05:21:59.610 回答