2016-03-01 71 views
1

我收到以下錯誤信息:迅速致命錯誤發現零

"fatal error: unexpectedly found nil while unwrapping an Optional value"

當我運行這部分代碼:

func askQuestion() { 
    button1.setImage(UIImage(named: cards[0]), forState: .Normal) 
    button2.setImage(UIImage(named: cards[1]), forState: .Normal) 
    button3.setImage(UIImage(named: cards[2]), forState: .Normal) 

    //title = cards[correctAnswer].uppercaseString 
} 

我不知道我做錯了或者問題是什麼。這是代碼的其餘部分:

import GameplayKit 
import UIKit 

class guessViewController: UIViewController { 

@IBOutlet weak var button1: UIButton! 
@IBOutlet weak var button2: UIButton! 
@IBOutlet weak var button3: UIButton! 
@IBOutlet weak var button4: UIButton! 

var cards = [String]() 
var score = 0 
var correctAnswer = 0 

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

    cards += ["boots", "tired", "heart", "angry", "leaf", "sleepy", "apple", "chestnuts", "pumpkin", "rainbow"] 

    askQuestion() 

    //cards = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(cards) as! [String] 

} 

func askQuestion() { 
    button1.setImage(UIImage(named: cards[0]), forState: .Normal) 
    button2.setImage(UIImage(named: cards[1]), forState: .Normal) 
    button3.setImage(UIImage(named: cards[2]), forState: .Normal) 

    //title = cards[correctAnswer].uppercaseString 
} 

@IBAction func buttonTapped(sender: UIButton) { 

    if sender.tag == correctAnswer { 
     score++ 
     print("correct") 

    } else { 

     score-- 
     print("incorrect") 

     } 
    } 
} 
+1

交叉檢查一次圖像名稱與您在卡片數組中指定的名稱相同。句法[0] =靴子不可用 –

回答

1

試試看看這個代碼。它會幫助你。

@IBOutlet weak var btn1: UIButton! 
@IBOutlet weak var btn2: UIButton! 

var cards = [String]() 

override func viewDidLoad() 
{ 
    super.viewDidLoad() 
    cards += ["11.jpg","1_home.jpg"] 
} 


@IBAction func btnAction(sender: AnyObject) 
{ 
    btn1.setBackgroundImage(UIImage(named: cards[0]), forState: UIControlState.Normal) 
    btn2.setBackgroundImage(UIImage(named: cards[1]), forState: UIControlState.Normal) 
} 
+0

謝謝。我的按鈕名稱被錯誤地命名 – Miguel

1

UIImage(name: "")返回一個可選項。因此,對於一個或多個按鈕,您將圖像設置爲nil並將其崩潰。檢查你的圖像的名稱,並確保它們存在。

相關問題