无法施放类型的价值' UIView' (0x10d54a4c0)到' UIButton' (0x10d552120)

时间:2017-02-17 01:06:42

标签: ios iphone swift uiview uibutton

有一个像这样的问题,但我尝试了这些建议,但它仍然不适合我。 :/

我正在尝试使用本教程制作测验应用:https://www.youtube.com/watch?v=KNAQ3Y8PGkM&t=1s

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

除了我收到错误外,一切都很完美:

  

无法投放类型的价值' UIView' (0x10d54a4c0)到' 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.
    }


}

1 个答案:

答案 0 :(得分:0)

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

请记住将3 UI按钮标记设置为1,2和3 看3:20

出现问题是因为您已将自己的View标记设置为=。

您可以通过将视图的标记值更改为数字来轻松修复!= 1,2和3

因为您的ViewController有2个视图,标记相同= 1.(viewUI Button)。 因此,当您使用view.viewWithTag(i)时,它会意外地选择view而不是UI Button。因此无法转换为UI Button类型

P / s:下次,如果您想直接选择按钮,可以使用@IBOutletButton制作Label。它不会像那样引起令人困惑的错误