在Swift中随机生成UIView每秒钟

时间:2016-02-11 01:59:03

标签: ios swift uibutton nstimer

我正在尝试"产生"一个UIView,随机的UIColor作为随机CGPoint的背景。我正在使用下面的代码编译好没有错误或任何东西,但当它在模拟器中运行时,我点击开始(第一个ViewController上的按钮),然后转到ViewTwo但没有任何反应(没有"敌人"产卵)。谢谢你的帮助。

import UIKit

var randomPoint: CGPoint = CGPoint(x: Int(arc4random()%1000), y: Int(arc4random()%1000))

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: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        enemy.backgroundColor = randomColor()
        enemy.center = randomPoint
        self.view.addSubview(enemy)
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}

1 个答案:

答案 0 :(得分:0)

你的randomPoint需要在spawnEnemy中重新计算,并且从0到1000生成一个随机的x y(也应该是一个浮点数)它可能会在屏幕外。