Reputation: 41
I tried to code a program which has two images. I use 4 buttons UP, DOWN, LEFT, RIGHT to move one image. If that image reaches the other, a text field will show up: "You are the winner!".
However, the line containing the code If... always gets "Expected Declaration" error. How can I make it run, pls?
This is the whole code, the names of two images are ConChimCu and Trung:
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.
}
Upvotes: 0
Views: 1838
Reputation: 816
Two things you are doing wrong here.
So here is the solution.
create function like
func checkCollision() {
if ConChimCu.frame.origin.x == Trung.frame.origin.x {
txtBai.text = "You are the winner!"
}
}
and call it from your every button action.
e.g.
@IBAction func Up(sender: AnyObject) {
ConChimCu.frame.origin.y = ConChimCu.frame.origin.y - 2
checkCollision()
}
Enjoy ;]
Upvotes: 0
Reputation: 121
Your if statement must be inside a function.
Example
func checkCollision() {
if ConChimCu.frame.origin.x == Trung.frame.origin.x {
txtBai.text = "You are the winner!"
}
}
Upvotes: 2