I have many no. of buttons on my view and I want to shuffle the buttons(change in position) then how can I shuffle the button in my view.
You can do this
In the layoutSubViews method set something like this:
-(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); }];
}
Then you will need to shuffle the positions in the positions array, you can see an example method here : How to Shuffle an Array
-(void)setNeedsLayout
on your view. There are more options but that was the first I thought of.
Good Luck
use arc4random()
and change position of your buttons
In your .h file
: UIButton *buttonsarray[10];
In your .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--;
}
}
}
Hope,this will help you..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.