为什么按钮不起作用

时间:2015-06-18 05:05:16

标签: ios xcode swift

“go按钮”无法正常工作。单击时,它应隐藏子视图。这是ViewController。我尝试将最终功能放在不同的地方。

class timeViewController: UIViewController {


var score = 0
var buttonState: Int = 0;
var gameOver = UIView()

@IBAction func start(sender: AnyObject) {

  if(displayTime.text != stoptimer.text){

        var gameOver = UIView(frame: CGRectMake(0, 0, 0, 0))
        gameOver.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
        //gameOver.opaque = false
        self.view.addSubview(gameOver)
        UIView.animateWithDuration(0, animations:{
            gameOver.frame.size = CGSizeMake(667, 667)
        })

        let gobutton = UIButton()
        let image = "button.png"
        gobutton.setImage(UIImage(named: image), forState: .Normal)
        gobutton.frame = CGRectMake(135, 300, 95, 95)
        gobutton.addTarget(self, action: "pressed:" , forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(gobutton)

        func pressed(sender: UIButton!){
             gameOver.removeFromSuperview()
        }
  }
}

3 个答案:

答案 0 :(得分:1)

要删除“GaneOver”视图,请更改此代码:

gameOver.removeFromSuperview()

我希望你在viewDidLoad或viewWillAppear之外写“func press”

答案 1 :(得分:1)

你必须通过在函数外声明它来使gameOver成为一个全局变量,然后按照你的方式做你所做的:

class myClass {
    var gameOver = UIView()

    func myFunction() {/*edit everything including gameOverView's properties*/}
    func pressed(sender: UIButton!) {
        gameOver.removeFromSuperview()
    }
}

还要确保在其他函数之外编写函数,例如viewDidLoad,但在类中,因为看起来你在另一个函数中创建了该函数。但是,你可以使用像myFunction()这样的单独行来调用另一个函数。

希望有所帮助:)

答案 2 :(得分:0)

你在if语句中重新声明了gameOver。只需删除var。检查此代码:

class ViewController: UIViewController {

var gameOver: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func start(sender: AnyObject) {

    if(displayTime.text != stoptimer.text){

        gameOver = UIView(frame: CGRectMake(0, 0, 0, 0))
        gameOver.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
        //gameOver.opaque = false
        self.view.addSubview(gameOver)
        UIView.animateWithDuration(0, animations:{
            self.gameOver.frame.size = CGSizeMake(667, 667)
        })

        let gobutton = UIButton()
        let image = "button.png"
        gobutton.setImage(UIImage(named: image), forState: .Normal)
        gobutton.frame = CGRectMake(135, 300, 95, 95)
        gobutton.addTarget(self, action: "pressed:" , forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(gobutton)

    }
}

func pressed(sender: UIButton!){
    self.gameOver.removeFromSuperview()
}
}