Ios 选择带有数字的特定按钮

Ios 选择带有数字的特定按钮,ios,objective-c,uibutton,Ios,Objective C,Uibutton,我有一个有35个按钮的项目: IBOutlet UIButton *button1; IBOutlet UIButton *button2; IBOutlet UIButton *button3; ... IBOutlet UIButton *button35; 在我的例子中,我正在创建一个函数,该函数将从0-35中选择一个数字,并尝试根据生成的数字选择按钮,如下所示: int x = arc4random() % 35; button[x].laye

我有一个有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];

但代码不起作用,因为我认为我无法选择按钮,如何解决此问题并选择按钮并更改边框颜色?

您可以设置每个按钮的标记字段并根据标记查找按钮:

int x = arc4random() % 35;
UIButton * desiredButton = (UIButton *)[self.view viewWithTag:x];
desiredButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
在这种情况下,您还可以使用IBOutletCollection来避免有35个按钮定义:

IBOutletCollection(UIButton) NSArray * _buttonsArray;

我建议从某个固定的偏移量开始为按钮分配顺序标记,然后使用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];

因为我看到您使用outlet设置按钮,所以我建议您也定义一个
IBOutletCollection
属性,并使用该属性获取随机按钮(在outlet集合中,顺序不确定,但随机选择不需要):


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;
}