本文介绍了Swift:标签文字-> “致命错误:在展开可选值时意外发现nil".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
就像标题中所说的,我试图在单击按钮时更改标签文本.错误出现在self.playerChoice.text = "You: Rock"
like it says in the title, i am trying to change label text upon click of a button. Error appears at line self.playerChoice.text = "You: Rock"
import UIKit class ViewController: UIViewController { var player : Int = Int() @IBOutlet weak var readyLabel: UILabel! @IBAction func noButton(sender: AnyObject) { exit(0) } // --------------------------------------------------------- @IBOutlet var computerChoice: UILabel! @IBOutlet var playerChoice: UILabel! @IBOutlet var score: UILabel! // Variables ------------------------------------------------- let Rock : String = "Rock" let Paper : String = "Paper" let Scissors : String = "Scissors" //------------------------------------------------------------ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } // ---------------------------------------------------------------- @IBAction func rockButton(rockbut: UIButton) { player = 0 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Rock" } @IBAction func paperButton(paperbut: UIButton) { player = 1 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Paper" } @IBAction func scissorsButton(scissorsbut: UIButton) { player = 2 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Scissors" } }推荐答案
我已经尝试了这段代码,并且对我来说很好用:
I have tried this code and it working fine for me:
class ViewController: UIViewController { var player : Int = Int() //Declare this globally @IBOutlet weak var readyLabel: UILabel! @IBAction func noButton(sender: AnyObject) { exit(0) } // --------------------------------------------------------- @IBOutlet var computerChoice: UILabel! @IBOutlet var playerChoice: UILabel! @IBOutlet var score: UILabel! // Variables ------------------------------------------------- let Rock : String = "Rock" let Paper : String = "Paper" let Scissors : String = "Scissors" //------------------------------------------------------------ @IBAction func rockButton(rockbut: UIButton) { player = 0 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Rock" } @IBAction func paperButton(sender: UIButton) { player = 1 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Paper" } @IBAction func scissorsButton(sender: UIButton) { player = 2 var ai = arc4random_uniform(3) self.playerChoice.text = "You: Scissors" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var p : String = "Undecided" if (player == 0) { var p: String = "Rock" } else if (player == 1) { var p: String = "Paper" } else if (player == 2) { var p: String = "Scissors" } } }更多推荐
Swift:标签文字
发布评论