xiaolingxiao
xiaolingxiao

Reputation: 4895

Cannot connect to UITextField

I am making a basic currency conversion app in an attempt to learn ios development, but cannot figure out how to listen to UITextField events. this is my code so far:

//
//  ViewController.swift
//  Currency
//

import UIKit

class ViewController: 

      UIViewController

    , UIPickerViewDelegate
    , UIPickerViewDataSource 

    , UITextViewDelegate

    , UITextFieldDelegate

    {

    @IBOutlet var pickerView     : UIPickerView!
    @IBOutlet var inputTextField : UITextField!
    @IBOutlet weak var outputText: UILabel!


    // definface pickerdata : note it's a constant
    let pickerData = ["euro", "us-dollar", "yen", "yuan", "peso"]

    // initialize src and tgt currency with listeners
    // note not sure what to do with these observers yet
    var src : String = "" // { did set {} }
    var tgt : String = "" 

    override func viewDidLoad() {

        super.viewDidLoad()

        // instance of this class is source of data
        pickerView.dataSource   = self
        pickerView.delegate     = self

        // match default srce and tgt to ios default
        src = pickerData[0]
        tgt = pickerData[0]

        // disable spell check
        inputTextField.autocorrectionType = UITextAutocorrectionType.no

    }

    //MARK: -  UIPickerView data source method
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        // number of components in pickerData
        return 2
    }

    // UIPickerViewDelegate methods
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        // number of rows
        return pickerData.count
    }

    //MARK: Delegates - places data into picker
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    // responding to row selections and also need to write to UILabel
    // NOTE: we need to 
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if component == 0 { src = pickerData[row] } 
        else              { tgt = pickerData[row] }

        let rate = Data.getExchangeRate(inputUnit: src, outputUnit: tgt)

        print (">> (src,tgt): (", src, ",", tgt, ")   value: ", inputTextField.text)
        outputText.text = "hello world"

    }


    //MARK: - UITextFieldDelegate  methods
    func textFieldShouldBeginEditing(_ textField : UITextField) -> Bool{
        print("TextField did begin editing method called")
        return true
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

        print("textField changing")
        return true
    }    

}

The functions under //MARK: - UITextFieldDelegate methods should fire when I edit the text field, but is not doing so right now. Any thoughts?

Upvotes: 0

Views: 394

Answers (2)

luckyShubhra
luckyShubhra

Reputation: 2751

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object.

The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled.

The delegate may respond to the message by updating the appearance or state of itself or other objects in the application.

The delegating class has an outlet or property, usually one that is named delegate. The delegating class declares methods on a category of NSObject, and the delegate implements only those methods in which it has an interest in coordinating itself with the delegating object or affecting that object’s default behavior.

I hope now you get why textfield delegate methods were not called. As you have not assigned your ViewController as delegate of inputTextField. Hence the message that inputTextField is just handled is not delivered to your ViewController.

You can check this link to know more about Delegate. To know how delegation pattern works check this link.

You can set your class as delegate of textfield as

inputTextField.delegate = self;

-----EDIT----

how to detect what the current text is in the text field?

In viewDidLoad add

inputTextField.addTarget(self, action: #selector(typingInput), for: .editingChanged)

Define method as

func typingInput(textField:UITextField){
    if let typedText = textField.text {        
        print(typedText ) // get the current string
    }
}

Credits to this ans.

Upvotes: 2

Bilal
Bilal

Reputation: 19156

Set inputTextField delegate.

inputTextField.delegate = self

Upvotes: 4

Related Questions