如何将按钮的标签设置为等于 Objective-C 的整数?

How can I set a button's tag equal to an integer with Objective-C?

我已经使用 arc4random() 生成了一个随机数,我想将该数字与每个 UIButton 按下时的数字进行比较。我已将每个按钮的 tag 设置为等于它代表的数字。

我生成了一个随机数 1-9 不包括 5:

- (NSInteger)winningNumber {
    do{
        _winningNumber = arc4random() %10 +1;
    }
    while (_winningNumber ==5);
    return _winningNumber;
}

我有 UIButton 1-4 和 5-9,它们被相应地标记了。当我按下一个按钮时,我想将该按钮的标签用于随机数。

你可以从你的按钮中调用这样的东西:

- (int)getNumberFromButton:(UIButton *)button
{
  return (int)button.tag;
}

您的按钮设置与此类似(您可以使用 IB 来实现类似的事情)

UIButton *exampleButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
exampleButton.tag = 1;

    [exampleButton addTarget:self
                      action:@selector(getNumberFromButton:)
            forControlEvents:UIControlEventTouchUpInside];

您可以在Button 的IBAction 方法上获取标签值。在这里你可以access/modify标签值:

- (IBAction)btnPressed:(id)sender
{
   UIButton *button = (UIButton *)sender;
   NSInteger tagValue = button.tag;

   //here you can assign new tag value to this button as well
   button.tag =  [self winningNumber];
}