按照 iOS编程:《大书呆子牧场指南》(第6版)的指南,我尝试快速制作一个Quiz项目。
此处的ViewController代码
import UIKit
class ViewController: UIViewController {
@IBOutlet var questionLabel: UILabel!
@IBOutlet var answerLabel: UILabel!
let questions: [String] = [
"What is 7+7?",
"What is the capital of Vermont?",
"What is cognac made from?"
]
let answers: [String] = [
"14",
"Montpelier",
"Grapes"
]
var currentQuestionIndex: Int = 0
@IBAction func showNextQuestion(_ sender: UIButton) {
currentQuestionIndex += 1
if currentQuestionIndex == questions.count {
currentQuestionIndex = 0
}
let question: String = questions[currentQuestionIndex]
questionLabel.text = question
answerLabel.text = "???"
}
@IBAction func showAnswer(_ sender: UIButton) {
let answer: String = answers[currentQuestionIndex]
answerLabel.text = answer
}
override func viewDidLoad() {
super.viewDidLoad()
questionLabel.text = questions[currentQuestionIndex]
}
}
但可以使用非可视文本(int文本除外)运行。
答案 0 :(得分:1)
我已经通过演示项目检查了您的代码,并且工作正常。而您的问题是您在UI components
中添加的storyboard
。
将约束分配给您的questionLabel
,如下图所示:
基本上,我已经分配了Leading
,Trailing
Top
和Height
约束以标记并将Alignment
设置为center
。
与其他标签和按钮相同。而且看起来会很好。
有关更多信息,请检查THIS演示项目以及您的代码。
答案 1 :(得分:0)