简体   繁体   中英

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

I'm trying to create a dictionary-like app using a dictionary with multiple key - value pairs. The idea is when the user types and existing key in the textField and clicks the button the value of that key is displayed on the label . I could only get to display all the entries (including keys and values) when button is clicked (irrespective of the content of the textField ), but that's not what I'm trying to achieve.

Here's my code:

//
//  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]

In your @IBAction you should try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM