按照 iOS 编程:The Big Nerd Ranch 指南,第 6 版 的指南,我尝试使用 swift 制作一个测验项目。
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 之外,使用非可视文本运行。
最佳答案
我已经用演示项目检查了你的代码,它工作正常。你的问题是你在 storyboard
中添加的 UI components
。
为您的 questionLabel
分配约束,如下图所示:
基本上我已经分配了 Leading
, Trailing
Top
和 Height
约束来标记和设置 Alignment
到中心
。
其他标签和按钮也一样。而且看起来会很好。
更多信息请查看THIS带有您的代码的演示项目。
关于ios - 显示 UILabel 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54086194/