当用户在 swift 的 textField 中输入键时,如何显示键的值

How to display the value of a key when user enters the key in textField in swift

我正在尝试使用具有多个 key-value 对的 dictionary 创建一个类似字典的应用程序。 这个想法是当用户在 textField 中键入并存在 key 并单击 buttonkeyvalue 显示在 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.
    }
}

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

displayMeaning.text = words[textField.text]

在您的 @IBAction 中,您应该试试这个:

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