gpt4 book ai didi

ios - 无法将类型 'UIView' (0x10d54a4c0) 的值转换为 'UIButton' (0x10d552120)

转载 作者:行者123 更新时间:2023-11-30 12:40:30 25 4
gpt4 key购买 nike

已经提出了这样的问题,但我尝试了这些建议,但它仍然对我不起作用。 :/

我正在尝试使用本教程制作一个测验应用程序: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.
}


}

最佳答案

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

记住将 3 个 UI 按钮的标签设置为 1、2 和 3观看 3:20

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

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

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

P/s:下次,如果您想直接选择按钮,您可以像使用 一样为该 Button 创建一个 @IBOutlet标签。它不会导致像这样令人困惑的错误

关于ios - 无法将类型 'UIView' (0x10d54a4c0) 的值转换为 'UIButton' (0x10d552120),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com