[英]iPhone:How can I shuffle buttons in view
我有很多沒有。 上的按鈕,並且我想隨機播放按鈕(位置變化),然后如何在視圖中隨機播放按鈕。
你可以這樣做
在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); }];
}
然后您將需要對位置數組中的位置進行混洗,您可以在此處看到示例方法: 如何對數組進行混洗
-(void)setNeedsLayout
。 還有更多選擇,但這是我想到的第一個。
祝好運
使用arc4random()
並更改按鈕的位置
在您的.h file
: UIButton *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.