2016-04-26 106 views
0

我试图编写一个包含两个图像的程序。我使用4个按钮上,下,左,右移动一个图像。 如果该图像到达另一个图像,文本字段将显示:“您是赢家!”。Swift中的“预期声明”

但是,包含代码If ...的行始终得到“Expected Declaration”错误。我如何让它运行,请问?

这是整个代码,两个图像的名称ConChimCu和忠:

import UIKit 

class ViewController: UIViewController { 
    @IBOutlet weak var txtBai: UITextView! 
    @IBOutlet weak var ConChimCu: UIImageView! 
    @IBOutlet weak var Trung: UIImageView! 

    @IBAction func Up(sender: AnyObject) { 
     ConChimCu.frame.origin.y = ConChimCu.frame.origin.y - 2 
    } 

    @IBAction func RIGHT(sender: AnyObject) { 
     ConChimCu.frame.origin.x = ConChimCu.frame.origin.x + 2 
    } 

    @IBAction func DOWN(sender: AnyObject) { 
     ConChimCu.frame.origin.y = ConChimCu.frame.origin.y + 2 
    } 

    @IBAction func LEFT(sender: AnyObject) { 
     ConChimCu.frame.origin.x = ConChimCu.frame.origin.x - 2 
    } 

    if ConChimCu.frame.origin.x == Trung.frame.origin.x { txtBai.text = "You are the winner!" 
    } 

    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. 
    } 
+0

[预期宣言错误的可能的复制的Xcode 6.2使用夫特(http://stackoverflow.com/questions/29835490/expected-declaration-error-xcode-6-2-使用迅速) – vadian

回答

2

你的if语句必须是一个函数里面。

 


    func checkCollision() { 
     if ConChimCu.frame.origin.x == Trung.frame.origin.x { 
      txtBai.text = "You are the winner!" 
     } 
    } 

 
+1

我怀疑这就是他需要的。他也应该在每一步之后调用这个功能。 –

+0

我按照你的意见,错误不再显示。但是当“ConChimCu”达到“Trung”时,文字“你是赢家”并没有出现。 我还修正了“func checkCollition()”到“func checkCollision()”,但没有任何事情发生。 –

+0

你做了什么@EvazhanMustafa建议? – Kingslayerpy

0

两件事情你是做错了。

  1. 您已经写出了超出函数范围的IF条件。 (如@Kingslayerpy建议)
  2. 即使更正后如果条件你没有叫它。 (根据我的理解根据您的意见)

所以这里是解决方案。

func checkCollision() { 
    if ConChimCu.frame.origin.x == Trung.frame.origin.x { 
     txtBai.text = "You are the winner!" 
    } 
} 

创建功能,并从你的每一个按钮动作调用它。

例如

@IBAction func Up(sender: AnyObject) { 
    ConChimCu.frame.origin.y = ConChimCu.frame.origin.y - 2 
    checkCollision() 
} 

享受;