我有一个更长的代码,每隔一段时间就会将UIButton产生到UIViewController上。但是现在我要做的是将backgroundColor从随机颜色转换为UIColor.whiteColor()。我可以创建一个函数来执行这个单击的UIButton,但是对于我生成的每一个UIButton都可以工作。或者更容易使用与UIButtons相反的UIViews并采用不同的路径?谢谢。
import UIKit
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y: CGFloat(arc4random()%528))
return randomPoint
}
class ViewController: UIViewController {
@IBOutlet weak var startGameButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class ViewTwo : UIViewController {
var timer = NSTimer()
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIButton = UIButton(frame: CGRect(x: 320, y: 320, width: 25, height: 25))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPressed"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
// or my buttonPressed func goes but either way the app crashes when i click on one of the UIButtons
override func viewDidLoad() {
super.viewDidLoad()
func buttonPressed(sender: UIButton) {
sender.backgroundColor = UIColor.whiteColor()
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:2)
当您创建按钮以生成它们时,您可以添加如下目标:
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
然后添加相应的功能将背景颜色更改为白色,如下所示:
func buttonClicked(sender: UIButton) {
sender.backgroundColor = UIColor.whiteColor()
}
这适用于您生成的所有按钮。