【问题标题】:Display questions from an array in order on a button press in swift在快速按下按钮时按顺序显示数组中的问题
【发布时间】:2015-03-17 00:07:37
【问题描述】:

我是学习 iOS Swift 的新手,如果这很容易,敬请见谅。

我的应用首页布局简单:

UILabel(我的问题) UITextField(用户写答案的地方) UIButton(用户在文本字段中输入后激活)

我已经提出了 4 个问题。我正在尝试编写代码,当用户按下 UIButton 时,只要已填充文本字段,它将在数组中显示下一个问题。

这是我目前所拥有的:

@IBOutlet var textField: UITextField!

@IBOutlet var questionLabel: UILabel!

@IBOutlet var buttonLabel: UIButton!

let questions = ["Where are you going?", "Do you know what city?", "What are you doing there?", "When do you go?"]


@IBAction func nextButton(sender: AnyObject) {

    textField.hidden = false
    textField.placeholder = "Country"


    for var i = 0; i < 5; i++ {
        questionLabel.text = questions[0]
    }

    buttonLabel.setTitle("Next", forState: UIControlState.Normal)

  }

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //keyboard
    textField.delegate = self

    buttonLabel.setTitle("Get Started", forState: UIControlState.Normal)
    questionLabel.text = ""

    // Hides the text field
    textField.hidden = true

    // Hides the image background for the text field
    barImage.hidden = true

}

我能够做到,所以当用户按下“开始”按钮时,它会将按钮文本更改为“下一步”,显示文本字段和数组中的第一个问题。

但是,一旦用户输入答案并按下“下一步”按钮,我无法弄清楚如何转到下一个问题。

非常感谢任何帮助。

尼克

【问题讨论】:

    标签: ios iphone arrays swift uibutton


    【解决方案1】:

    添加一个名为currentQuestionIndex 的属性来跟踪您在数组中的位置,并在您单击按钮时增加它:

    var currentQuestionIndex = 0
    
    @IBAction func nextButton(sender: AnyObject) {
    
        textField.hidden = false
        textField.placeholder = "Country"
    
        questionLabel.text = questions[currentQuestionIndex]
    
        if currentQuestionIndex < questions.count {
             ++currentQuestionIndex
             buttonLabel.setTitle("Next", forState: UIControlState.Normal)
        } else {
            (sender as UIButton).userInteractionEnabled = false
        }
    
    }
    

    【讨论】:

    • 有没有办法禁用下一步按钮,除非文本字段中有答案?我试过这样的事情:如果 textField == nil { nextButton.enabled = false} - 但它似乎不起作用......?谢谢
    • 确定textField.userInteractionEnabled = false
    • 嗨,当我运行上面的行时,它只是禁止用户在文本字段中输入。我想要的是,在文本字段中写入内容之前禁用“下一步”按钮。
    • userInteractionEnabled 适用于UIView 的所有后代,因此只需将其应用于UIButton
    • 嗨,我确定是我太笨了,但是无论我把它放在哪里,我都无法让它做我需要的事情。你能告诉我它需要在上面的代码中去哪里吗?非常感谢
    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 2021-05-13
    • 2017-02-06
    • 2016-09-02
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多