随机播放NSMutableArray而不重复,并显示在UIButton中 [英] shuffle NSMutableArray without repetition and showing in a UIButton
本文介绍了随机播放NSMutableArray而不重复,并显示在UIButton中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我看来,我有12个按钮,并且一个数组包含6个名称,我想在 UIButton
标题中打印数组名称.这是我的代码:
In my view, i have 12 buttons,and a array contains 6 names , i want to print the array names in UIButton
title. Here's my code:
texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
UIButton *button;
NSString *name;
NSUInteger count = [texts count];
int i=0;
for(UIView *view in self.view.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
button= (UIButton *)view;
if(button.tag >= 1||button.tag <= 20)
{
int value = rand() % ([texts count] -1) ;
int myTag= i+1;
button = [self.view viewWithTag:myTag];
name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:value]];
[button setTitle:name forState:UIControlStateNormal];
NSLog(@"current name :%@",name);
}
i++;
}
}
[super viewDidLoad];
我面临的问题是:
-
在重排值时,我尝试使用改组NSMutableArray的最佳方法是什么?,它不起作用.
我想在12个按钮中包含6个标题,这意味着每个标题将在2个按钮中.请帮我解决这个问题.我应该进行哪些更改?
I want 6 titles in 12 button that means each title will be in 2 buttons. Please help me solve this issue. What changes should I make?
推荐答案
基本上,您需要将改组逻辑与为按钮功能添加名称分开.因此,请先随机排列数组,然后设置按钮的名称.
Basically you need to separate the shuffling logic from adding name to button feature. So first shuffle the array and then set the name of buttons.
[super viewDidLoad]; //Always super call should be the first call in viewDidLoad
texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", @"1",@"2",@"3",@"4",@"5",@"6", nil];
//adding all 12 button titles to array, use your own logic to create this array with 12 elements if you have only 6 elements
NSUInteger count = [texts count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
NSInteger nElements = count - i;
NSInteger n = (arc4random() % nElements) + i;
[texts exchangeObjectAtIndex:i withObjectAtIndex:n];
}
UIButton *button = nil;
NSString *name = nil;
int i = 0;
for(UIView *view in self.view.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
button= (UIButton *)view;
if(button.tag >= 1 && button.tag <= 20)
{
name = [NSString stringWithFormat:@"%@",[texts objectAtIndex:i]];
//assuming that the above texts array count and number of buttons are the same, or else this could crash
[button setTitle:name forState:UIControlStateNormal];
NSLog(@"current name :%@",name);
i++;
}
}
}
这篇关于随机播放NSMutableArray而不重复,并显示在UIButton中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文