简体   繁体   English

如何快速制作一个功能,以解决将在ViewController上出现的所有UIButton

[英]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. 我有一个更长的代码,每隔一定的时间就会将UIButtons生成到UIViewController上。 But now what I am trying to do is turn their backgroundColor from a random color to UIColor.whiteColor(). 但是现在我想做的是将它们的backgroundColor从随机颜色变成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? 我可以制作一个函数来对被单击的UIButton进行此操作,但可以对我“生成”的每个UIButton都起作用。还是使用相对于UIButton的UIView并采用不同的路径更容易? 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. 这将适用于您产生的所有按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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