[英]iPhone:How can I shuffle buttons in view
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: 在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); }];
} }
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. 现在,每次您需要调整位置时,都可以在视图上调用-(void)setNeedsLayout
。 There are more options but that was the first I thought of. 还有更多选择,但这是我想到的第一个。
Good Luck 祝好运
use arc4random()
使用arc4random()
and change position of your buttons 并更改按钮的位置
In your .h file
: UIButton *buttonsarray[10];
在您的.h file
: UIButton *buttonsarray[10];
In your .m file
: 在您的.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.. 希望这个能对您有所帮助..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.