【问题标题】:How to display the value of a key when user enters the key in textField in swift当用户在文本字段中快速输入键时如何显示键的值
【发布时间】:2015-07-21 12:38:44
【问题描述】:

我正在尝试使用带有多个 key-value 对的 dictionary 创建一个类似字典的应用程序。 这个想法是当用户在textField 中键入和现有key 并单击button 时,key 上的value 会显示在label 上。我只能在单击button 时显示所有条目(包括键和值)(无论textField 的内容如何),但这不是我想要实现的目标。

这是我的代码:

//
//  ViewController.swift
//  Dictionary
//
//  Created by Ralph on 7/20/15.
//  Copyright (c) 2015 Ralph. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    let words = [
        “doe” : “a deer, a female deer”,
        “ray" : “a drop of golden sun”,
        “me” : “a name I call myself”
    ]

    @IBOutlet weak var textField: UITextField!        

    @IBAction func searchButton(sender: AnyObject) {
        displayMeaning.text = words.description
    }

    @IBOutlet weak var displayMeaning: UILabel!

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

【问题讨论】:

  • 我没有看到您正在检索文本字段中输入的键的值。

标签: ios swift uibutton uitextfield uilabel


【解决方案1】:

您需要像这样访问文本字段中的文本

displayMeaning.text = words[textField.text]

【讨论】:

  • 非常感谢@Neil Horton,这行简短的代码解决了我的问题,并且完全符合我的要求。非常感谢您的帮助。
【解决方案2】:

在你的@IBAction 你应该试试这个:

@IBAction func searchButton(sender: UIButton) {
    displayMeaning.text = words.objectForKey(textField.text)
}

【讨论】:

  • 感谢@pbush25 的协助。但是,当我实施您的建议时,我收到一个错误:“[String : String]”没有名为“objectForKey”的成员。所以这并没有解决我的问题。
  • 对不起@Mandroid 它可能应该是words.valueForKey(textField.text)
  • 没关系,你只是想帮忙 ;-) 仍然得到一个错误。不过不用担心,问题已经解决了。感谢您的宝贵时间和帮助。
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 2011-12-10
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多