2014-10-08 90 views
0

我想只在代碼中添加一個按鈕。在Xcode模擬器它完美,但不是我的設備上:僅在代碼中添加按鈕?

fatal error: unexpectedly found nil while unwrapping an Optional value 

我的代碼:

@IBOutlet weak var playButton: UIButton! 

override func viewDidLoad() { 

    super.viewDidLoad() 

    let image = UIImage(named: "playButton.png") as UIImage 

    playButton = UIButton.buttonWithType(UIButtonType.System) as UIButton 
    playButton.frame = CGRectMake(10, 10, 100, 100) // crash is here 
    playButton.center = CGPointMake(self.frame.width/2, self.frame.height/1.7) 

    playButton.addTarget(self, action: "transition:", forControlEvents: UIControlEvents.TouchUpInside) 
    playButton .setBackgroundImage(image, forState: UIControlState.Normal) 

    self.view?.addSubview(playButton) 

} 

有人能幫助我嗎?

+0

這是什麼意思,它不適用於您的設備?說它不起作用是無用的。 – Fogmeister 2014-10-08 17:55:46

+0

我無法啓動它,我有一個致命錯誤:「致命錯誤:在解包可選值時意外發現零」 – Haox 2014-10-08 17:57:11

+0

您提供的代碼在哪裏?這是viewController的'viewDidLoad'方法中的代碼嗎? – Vinzzz 2014-10-08 18:09:11

回答

1

這是沒有意義的 - 如果你正在使用@IBOutlet這意味着你的按鈕在故事板創建的,因此你不需要初始化:

let image = UIImage(named: "playButton.png") as UIImage 

playButton = UIButton.buttonWithType(UIButtonType.System) as UIButton 
playButton.frame = CGRectMake(10, 10, 100, 100) // crash is here 
playButton.center = CGPointMake(self.frame.width/2, self.frame.height/1.7) 

playButton.addTarget(self, action: "transition:", forControlEvents: UIControlEvents.TouchUpInside) 
playButton .setBackgroundImage(image, forState: UIControlState.Normal) 

self.view?.addSubview(playButton) 

刪除所有上面的代碼和一套而不是故事板。 @IBAction應該是一個獨立的方法,它連接到你的故事板中按鈕的touchUpInside。

+0

謝謝!我刪除了@IBOutlet,因爲我只想在代碼中使用我的按鈕,而且它的工作原理與此類似。 – Haox 2014-10-08 19:11:35

+0

你知道我該如何在場景上添加按鈕?當我在我的GameScene中添加我的代碼(不帶@IBOutlet)時,該按鈕不會出現。你知道爲什麼嗎 ? – Haox 2014-10-08 19:25:26

+0

Haox,如果你指的是SpriteKit場景,我會檢查http:// stackoverflow。com/questions/19082202/setting-up-buttons-in-skscene回答 – Valentin 2014-10-09 11:11:51

1

「解開一個選項的值」似乎是指在您的var聲明旁邊......如果您使用,該怎麼辦?取而代之?

從斯威夫特DOC

Trying to use ! to access a non-existent optional value triggers a runtime error. 
Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. 

試試這個:

weak var playButton : UIButton? 

和補充的嗎?之後訪問它 - 就像你用self.view?.addSubview或本地強制解包與在你知道它已經創建

(我不知道,雖然,仍然在學習語言的方法... :-)

+0

感謝您的幫助,但它不起作用。 – Haox 2014-10-08 19:17:40

2

In the Xcode Simulator it works perfectly but not on my device

這通常意味着你有之間的不匹配您的代碼和文件的實際名稱。 MacOS X文件系統通常是而不是區分大小寫,而iOS文件系統區分大小寫。所以,如果你的圖像文件被命名爲PlayButton.pngplayButton.PNG,但你指定playButton.png,它通常會在模擬器上工作,但不在設備上。

確保代碼中的文件名與項目中的文件相匹配。

+0

謝謝!我知道區分大小寫,但這不是問題。我查過了,沒關係 – Haox 2014-10-08 19:08:37