简体   繁体   中英

How to make a function in swift that addresses all UIButtons that will ever be on the ViewController

I have a longer code that spawns UIButtons onto the UIViewController every certain amount of time. But now what I am trying to do is turn their backgroundColor from a random color to UIColor.whiteColor(). Hw could I make a function that will do this to the UIButton that is clicked on but will work for every single UIButton I "spawn" in. Or is it easier to use UIViews opposed to UIButtons and take a different path? Thank you.

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()

    }
}

When you're creating your buttons to spawn them you can add a target like this:

button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

And then add the corresponding function to change the background color to white like this:

func buttonClicked(sender: UIButton) {
    sender.backgroundColor = UIColor.whiteColor()
}

This will work for all buttons you spawn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM