如何通过标签操作 UIButtons

How to manipulate UIButtons via tag

我正在尝试为井字游戏创建一个简单的 AI,该游戏已经允许两名玩家通过九个不可见按钮 select。使用 sender.tag 我可以设置每个按钮的背景以显示 'X' 或 'O.'

现在我想创建一个 AI,但我不知道如何根据 AI selection 设置每个按钮的背景。我试图通过标签参数来做到这一点,但它不起作用,因为没有发件人。

处理背景(或没有名称的 UIButton 的任何参数)的最佳方法是什么?

谢谢, 马特

通过标签识别 UI 元素不是最佳做法。如果您使用 Interface Builder 设计 UI,那么您可以将这些 UIButtons 分配给一个 UIButton outlets 数组,这样您就可以访问应该被操作的必要对象。

1) 声明一个出口数组:

@IBOutlet var buttons: [UIButton]!

2) 在 Interface Builder 中将所有 UI 按钮按预定义的顺序连接到按钮插座

3) 使用 UI 按钮的扩展来改变它的颜色:

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color), forState: state)
    }
}

4) 然后在AI计算走法时从outlet数组中引用选择的UIButton:

buttons[int_of_AI_selected_button].setBackgroundColor(thecolor, forthecontrolstate)