0
import Foundation
import UIKit
class GameController: UIViewController {
@IBOutlet weak var gameImage: UIImageView!
@IBOutlet weak var softButton: UIButton!
@IBOutlet weak var notButton: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
self.gameImage.image = UIImage(named: "king1")
}
//choose random image and set as game image
func randomGameImage() -> String {
//these arrays hold the image names
let kingArray = ["king1", "king2", "king3"]
let notArray = ["not1", "not2", "not3"]
//this number decides which array to pull from
let randomNumber = Int(arc4random_uniform(2))
//this number picks what image from the array
let imageNumber = Int(arc4random_uniform(3))
//holds the name of the image
var gameImageString:String
//sets image name
if randomNumber >= 1 {
gameImageString = kingArray[imageNumber]
}else{
gameImageString = notArray[imageNumber]
}
//sets image
self.gameImage.image = UIImage(named: gameImageString)
//returns name of image
return gameImageString
}
var bool = true
var score = 0;
var imageShowing:String = randomGameImage()//"king"
(使用實例方法「randomGameImage」上鍵入「GameController」;做你的意思是使用類型「GameController」的價值呢?)爲什麼我可以在其他函數的主體中調用我的函數,但不能在類中自己調用?
@IBAction func kingTapped(sender: AnyObject) {
if imageShowing.rangeOfString("king") != nil {
score += 1
scoreLabel.text = String(score)
imageShowing = randomGameImage()
}else{
performSegueWithIdentifier("gameOver", sender: bool)
}
}
@IBAction func notTapped(sender: AnyObject) {
if imageShowing.rangeOfString("not") != nil {
score += 1
scoreLabel.text = String(score)
imageShowing = randomGameImage()
}else{
performSegueWithIdentifier("gameOver", sender: bool)
}
}
}
有人能告訴我爲什麼我可以調用randomGameImage方法在其他方法但不在方法外。對不起,我是編程noob。
我沒有廣泛的編程術語知識。如果你不介意你能解釋一下...我可以使randomGameImage成爲類方法嗎?這似乎有點荒謬,我該如何使用我寫的函數/方法? – LearningCurve
你的'randomGameImage()'正在訪問一個實例屬性'self.gameImage',它可能還沒有被初始化。所以,刪除該行,你可以使它成爲一種類方法。在'func randomGameImage()'之前加上'class'即可。但是你需要修改其他部分。 – OOPer
因此,即使該方法不包含實例屬性,如果該參數是實例屬性,您也會得到相同的錯誤,對嗎? – LearningCurve