[英]How to make a function in swift that addresses all UIButtons that will ever be on the ViewController
我有一個更長的代碼,每隔一定的時間就會將UIButtons生成到UIViewController上。 但是現在我想做的是將它們的backgroundColor從隨機顏色變成UIColor.whiteColor()。 我可以制作一個函數來對被單擊的UIButton進行此操作,但可以對我“生成”的每個UIButton都起作用。還是使用相對於UIButton的UIView並采用不同的路徑更容易? 謝謝。
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()
}
}
創建按鈕以生成按鈕時,可以添加如下目標:
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
然后添加相應的功能,將背景顏色更改為白色,如下所示:
func buttonClicked(sender: UIButton) {
sender.backgroundColor = UIColor.whiteColor()
}
這將適用於您產生的所有按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.