【发布时间】:2021-05-12 10:49:19
【问题描述】:
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 ?", Answers: ["Bat","Aircraft","Cat","Pat"], Answer: 2),
Questions(Question: "What is a ant ?", Answers: ["Bat","Cat","Vegetable","Insect"], Answer: 4),
Questions(Question: "What is a Apple ?", Answers: ["Bat","Cat","Fruit","Pat"], Answer: 3),]
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 类中创建了一个对象并通过循环对四个按钮进行了编程,并在顶部创建了一些将答案分配给按钮的问题对于每个问题,但它们不显示分配的答案,而是显示预设的按钮名称。
一切正常,但选择问题方法无法正常工作,因为它依赖于按下按钮才能进入下一个问题。
按钮需要解决方案来显示分配给每个问题的答案。
提前谢谢你。
【问题讨论】:
标签: swift xcode button sprite-kit skspritenode