显示UILabel的文字

时间:2019-01-08 06:21:04

标签: ios swift

按照 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文本除外)运行。

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

我已经通过演示项目检查了您的代码,并且工作正常。而您的问题是您在UI components中添加的storyboard

将约束分配给您的questionLabel,如下图所示:

enter image description here

基本上,我已经分配了LeadingTrailing TopHeight约束以标记并将Alignment设置为center

与其他标签和按钮相同。而且看起来会很好。

有关更多信息,请检查THIS演示项目以及您的代码。

答案 1 :(得分:0)

不要将questionLabelanswerLabel的宽度限制为特定的数字。尝试正确设置约束,例如标签宽度等于viewController的宽度,如下面的屏幕截图所示。

enter image description here