我试图创建一个简单的人工智能为一个抽搐脚趾游戏,已经允许两个玩家从9个无形按钮中选择。使用sender.tag,我可以设置每个按钮的背景以显示“X”或“O”。
现在我想创建一个AI,但我不知道如何设置每个按钮的背景基础上的AI选择。我试图通过标记参数来完成这个任务,但是由于没有发送方,所以它无法工作。
处理背景(或没有名称的UIButton的任何参数)的最佳方法是什么?
谢谢,马特
发布于 2016-05-30 22:19:47
根据UI元素的标记识别UI元素并不是最佳实践。如果您使用Interface设计UI,那么您可以将这些UIButtons分配给一个UIButton插座数组,该数组允许您访问应该被操作的必要对象。
1)宣布一系列出口:
@IBOutlet var buttons: [UIButton]!2)接口生成器中的所有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)https://stackoverflow.com/questions/37534099
复制相似问题