我试图去学习做一个基本的货币转换应用ios
开发,但无法弄清楚如何倾听UITextField
事件。 这是我到目前为止的代码:
//
// 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
}
}
下的功能//MARK: - UITextFieldDelegate methods
应该火的时候,我编辑的文本字段,但不这样做现在。 有什么想法吗?