2017-02-17 63 views
0

有一个类似这样的问题,但我尝试了这些建议,但它仍然不适用于我。 :/无法将类型'UIView'(0x10d54a4c0)的值转换为'UIButton'(0x10d552120)

我尝试使用本教程做一个测验应用程序:https://www.youtube.com/watch?v=KNAQ3Y8PGkM&t=1s

下面是一个链接,下载我的项目:https://www.dropbox.com/s/bwvg6fyrrzudued/kat%20quiz.zip?dl=0

一切都是完美的,除了我的错误:

Could not cast value of type 'UIView' (0x10d54a4c0) to 'UIButton' (0x10d552120)

我真的很感谢一些帮助。我尝试了一切在我的知识和搜索,谢谢。 :)

import UIKit 

class ViewController: UIViewController { 

    let questions = ["What color is Courage the Cowardly Dog?", "What is the name of the woman that lives with Courage?", "What is the name of the man that lives with Courage?"] 
    let answers = [["Purple","Grey","Orange"],["Muriel", "Angela", "Elizabeth"], ["Eustace", "Robert", "Ezio"]] 

    //Variables 
    var currentQuestion = 0 
    var rightAnswerPlacement:UInt32 = 0 
    var points = 0 

    //Label 
    @IBOutlet weak var lbl: UILabel! 

    //Button 
    @IBAction func action(_ sender: AnyObject) { 

     if (sender.tag == Int(rightAnswerPlacement)) 
     { 
      print ("RIGHT!") 
      points += 1 
     } 
     else 
     { 
      print ("WRONG!!!!!!") 
     } 
     if (currentQuestion != questions.count) 
     { 
      newQuestion() 
     } 
     else{ 
      performSegue(withIdentifier: "showScore", sender: self) 
     } 
    } 

    override func viewDidAppear(_ animated: Bool) { 
     newQuestion() 
    } 



    //Function that displays new question 
    func newQuestion(){ 
     lbl.text = questions[currentQuestion] 
     rightAnswerPlacement = arc4random_uniform(3)+1 

     //Create a button 
     var button:UIButton = UIButton() 

     var x = 1 

     for i in 1...3 
     { 
      //Create a button 
      button = view.viewWithTag(i) as! UIButton 

      if (i == Int(rightAnswerPlacement)) 
      { 
       button.setTitle(answers[currentQuestion][0], for: .normal) 
      } 

      else 
      { 
       button.setTitle(answers[currentQuestion][x], for: .normal) 
       x = 2 
      } 

     } 
     currentQuestion += 1 
    } 



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

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
+0

请问您能澄清一下吗?我对编程超新颖。谢谢:) –

回答

0

您是否在故事板中创建了UI按钮? 您的YouTube视频,观看1:45

记住你的3 UI按钮的标签设置为1,2和3 手表3:20

,因为你已经设置你浏览的标签会出现您的问题= 1.

你可以通过改变视图的标签值的数量来解决它!= 1,2和3

因为你的ViewController有2查看同一个标签= 1 (viewUI Button)。 所以当你使用view.viewWithTag(i)时,无意中选择了view而不是UI Button。因此,它不能转换为UI Button

P/S:接下来的时间,如果你想直接选择按钮,就可以使一个@IBOutletButton当你做你的Label。它不会导致这样的混淆错误

+0

是的,我做到了这一点。我只是重新编辑它,但仍然有同样的问题:/ –

+0

在1:45,你选择了** UI Button **还是不小心选择了** UI View **? –

+0

我选择了UI按钮 –

相关问题