【发布时间】:2021-05-13 13:34:12
【问题描述】:
import UIKit
import SpriteKit
import GameplayKit
struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
QuestionFunction()
ButtonFuction()
PickQuestion()
}
@objc func QuestionFunction(){
Questions = [Question(Question: "What is a Car ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 3),
Question(Question: "What is a plane ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 2),
Question(Question: "What is a ant ?", Answers: ["Bat","Cat","Vegetable","Insect"], AnswerNumber: 4),
Question(Question: "What is a Apple ?", Answers: ["Bat","Cat","Fruit","Pat"], AnswerNumber: 3),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
@objc func ButtonFuction(){
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)
buttons.append(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)])
}
@objc func PickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
}
}
@objc func handleButton() {
print("")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
我创建了一个基于测验的游戏并手动编写了我的按钮,但不确定如何创建在按下按钮时可以处理的方法。
【问题讨论】:
-
什么是Button()?为什么要使用 UIKit 来制作按钮?
标签: swift xcode button sprite-kit skspritenode