Swift: label text --> “fatal error: unexpectedly found nil while unwrapping an Optional value”

后端 未结 5 1559
感情败类
感情败类 2021-01-17 20:10

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\"



        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 21:02

    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"
        }
    
    
        }
    
    }
    

提交回复
热议问题