【问题标题】:How to check if input from UITextField matches Core Data attribute in array?如何检查来自 UITextField 的输入是否与数组中的核心数据属性匹配?
【发布时间】:2016-03-15 00:55:17
【问题描述】:

我有一个核心数据对象,它有两个属性,问题和答案。我还有一个包含标签、UITextField 和按钮的视图。我想在标签中显示问题属性,然后在 UITextField 中键入该问题的答案属性以检查它是否正确。

因此,在 viewDidLoad 中,我对 Card 对象运行了一次提取,并将结果放入一个数组中。我遵循this Stack Overflow post 以弄清楚如何遍历数组以显示标签中的每个问题属性,但现在我不确定如何准确检查该问题的答案属性。以下是我的源代码:

var cardFetch = [Card]()
var count = 0
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet weak var inputText: UITextField!

@IBAction func nextButton(sender: AnyObject) {
    displayLabel.text = cardFetch[count%cardFetch.count].question
    count++
}

【问题讨论】:

    标签: ios arrays swift core-data


    【解决方案1】:

    尝试类似:

    @IBAction func nextButton(sender: AnyObject) {
       if let questionString = cardFetch[count%cardFetch.count].question as? String {
           displayLabel.text = questionString
           count++
       }   
    }
    
    @IBAction func checkAnswer(sender: AnyObject) {
        if let answerString = cardFetch[count%cardFetch.count].answer as? String {
            if let unwrappedTextfieldString = inputText.text as? String {  
                if answerString == unwrappedTextfieldString {
                   // Do whatever you want here
                }
            }
        }   
    }
    

    注意使可选解包崩溃安全的解包。

    【讨论】:

    • 如果我误解了,请原谅我,但我需要从我的数组中的 Card 对象访问 answer 属性。我正在访问要在标签中显示的问题属性,并且我想将与该问题相关的答案属性输入到文本字段中。
    • 请检查我的编辑。我不知道您的项目中的命名是什么,所以我不确定像 cardFetch[count%cardFetch.count].answer 这样的伪代码是否有效,但我的回答应该向您展示逻辑。
    • 只有当我删除 count++ 时似乎才有效。我应该以更简洁的方式而不是 cardFetch[count%cardFetch.count].answer 来做这件事吗?
    • 从您的问题中复制了 count++。你最好用这些按钮方法初始化变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2014-10-28
    相关资源
    最近更新 更多