如何通过标签操作UIButton

时间:2016-05-30 21:57:58

标签: ios8 swift2

我试图为一个tic tac toe游戏创建一个简单的AI,它已经允许两个玩家从九个隐形按钮中进行选择。使用sender.tag我可以设置每个按钮的背景以显示' X'或者' O。'

现在我想创建一个AI,但我不知道如何根据AI选择设置每个按钮背景。我尝试通过tag参数执行此操作,但由于没有发件人,因此无法正常工作。

操作背景(或没有名字的UIButton的任何参数)的最佳方法是什么?

谢谢, 马特

1 个答案:

答案 0 :(得分:0)

通过标签识别UI元素不是最佳做法。如果使用Interface Builder设计UI,则可以将这些UIButtons分配给UIButton出口阵列,然后允许您访问应该操作的必要对象。

1)声明一系列出口:

@IBOutlet var buttons: [UIButton]!

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

3)使用UIButton的扩展名来改变颜色:

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计算移动时,从插座阵列引用所选的UIButton:

buttons[int_of_AI_selected_button].setBackgroundColor(thecolor, forthecontrolstate)
相关问题