如何解决编程的 Swift 按钮没有显示正确的文本?
import UIKit
import SpriteKit
import GameplayKit
struct Questions {
var Question : String!
var Answers : [String]!
var Answer : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question = UILabel(frame: CGRect(x: 0.3,y: 0.3,width: 40,height: 21))
var Questionss = [Questions]()
var QNumber = Int()
var buttonNames = [""]
override func didMove(to view: SKView) {
// Button code
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for name in buttonNames {
button = Button()
button.setTitle(name,for: .normal)
stacView.addArrangedSubview(button)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
// Question and Answer Code
Questionss = [Questions(Question: "What is a Car ?",Answers: ["Bat","Cat","Vehicle","Pat"],Answer: 3),Questions(Question: "What is a plane ?","Aircraft",Answer: 2),Questions(Question: "What is a ant ?","Vegetable","Insect"],Answer: 4),Questions(Question: "What is a Apple ?","Fruit",]
Question.frame = CGRect(x: 330,y: 70,width: 200,height: 21)
Question.backgroundColor = UIColor.orange
Question.textColor = UIColor.white
Question.textAlignment = NSTextAlignment.center
Question.text = "What caused Global Warming ?"
self.view?.addSubview(Question)
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2,y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
PickQuestion()
}
@objc func PickQuestion(){
if Questionss.count > 0{
QNumber = 0
Question.text = Questionss[QNumber].Question
for i in 0..<buttons.count{
buttons[i].setTitle(Questionss[QNumber].Answers[i],for: UIControl.State.normal)
}
Questionss.remove(at: QNumber)
} else {
print("Done!")
}
}
@objc func handleButton() {
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
}
}
我创建了一个按钮类并设置了按钮的参数以及它在屏幕上的显示方式。在这个 levelOne 类中创建了一个对象并通过循环对四个按钮进行编程,并在顶部创建了一些将答案分配给按钮的问题对于每个问题,但它们不显示分配的答案,而是显示预设的按钮名称。
一切正常,但选择问题方法无法正常工作,因为它依赖于按下按钮才能进入下一个问题。
需要按钮的解决方案来显示为每个问题分配的答案。
提前致谢。
解决方法
您从未将每个按钮添加到 buttons
...
for name in buttonNames {
button = Button()
button.setTitle(name,for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
我还强烈建议您研究基本的 Swift 代码编写实践。类似的东西
- camelCase 命名实践
- 变量命名而不是
Questions
vsQuestionss
- 初始化为 1 个项目 - 所以你的结构将是
Question
并且它会包含title:String
、answers:[String]
和answerNumber:[Int]
然后你可以有一个 {{1} 的数组}s. - 将代码分解成块,即函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。