我有一个有35个按钮的项目:
IBOutlet UIButton *button1;
IBOutlet UIButton *button2;
IBOutlet UIButton *button3;
...
IBOutlet UIButton *button35;
在我的情况下,我正在创建一个从0-35中选择一个数字的函数,我正在尝试根据生成的数字选择按钮,如下所示:
int x = arc4random() % 35;
button[x].layer.borderColor = [[UIColor darkGrayColor] CGColor];
但是代码不起作用,因为我相信我无法选择按钮,如何解决这个问题并选择按钮并更改边框颜色?
答案 0 :(得分:1)
您可以设置每个按钮的标记字段,并根据标记查找按钮:
int x = arc4random() % 35;
UIButton * desiredButton = (UIButton *)[self.view viewWithTag:x];
desiredButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
在这种情况下,您还可以使用IBOutletCollection来避免使用35个按钮定义:
IBOutletCollection(UIButton) NSArray * _buttonsArray;
答案 1 :(得分:1)
我建议按照某个固定的偏移量为你的按钮分配顺序标签,然后使用viewWithTag按照DanielM的替代建议中的建议来获取按钮。
#define K_TAG_BASE 100 //BUTTON TAGS START AT 100
int tag = arc4random() % 35 + K_TAG_BASE;
NSButton aButton = [self.view viewWithTag: tag];
aButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
答案 2 :(得分:0)
由于我看到您设置了带插座的按钮,我建议您还定义一个IBOutletCollection
属性并使用它来获取一个随机按钮(在插座集合中,订单无法保证,但您不需要随机选择):
// In your class @interface
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttonsArray;
// In your class @implementation
-(void)selectRandomButton
{
NSInteger randomIndex = arc4random() % self.buttonsArray.count;
((UIButton *)self.buttonsArray[randomIndex]).layer.borderColor = [UIColor darkGrayColor].CGColor;
}