如何创建一个可以容纳多个值的文本字段,例如,电子邮件至:包含多个收件人电子邮件地址的字段

时间:2019-06-15 13:16:57

标签: swift uipickerview textfield

我有一个UITextField,它具有pickerview作为inputview。Pickerview显示来自存储在NSUSERDEFAULTS中的字符串数组中的数据(例如[“ horse”,“ cat”,“ camel”,“ cow”,“ parrot”,“孔雀” ])。我需要从选择器中选择多个值,并将其显示在单个UITextField中,例如在电子邮件发送至:字段中。 您能为此提供一些输入吗?

当前无法从选择器中选择一个值并将文本字段设置为该值。需要了解如何从选择器的单个组件中选择多个值并将其设置为单个文本字段。

PFB我尝试过的代码

class ViewController: UIViewController,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource {



    var item = String()
    var itemsaved = [String]()

    @IBOutlet var searchTextField: UITextField!
    @IBOutlet var picker: UIPickerView!


    let itemArray = ["camel","cow","horse","duck","parrot","peacock"]
    let defaults = UserDefaults.standard


    override func viewDidLoad() {

        super.viewDidLoad()
        defaults.set(itemArray, forKey: "stringArray")
        self.searchTextField.inputView = picker
        picker.removeFromSuperview()
        self.picker.translatesAutoresizingMaskIntoConstraints = false
        self.searchTextField.delegate = self

        searchTextField.addTarget(self, action: #selector(ViewController.editingchanged(_:)),
                                  for: UIControl.Event.editingChanged)
    }


    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.itemsaved.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return self.itemsaved[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.searchTextField.text = self.itemsaved[row]
        self.view.endEditing(true)


    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }



    func retreivedata(sender:UITextField) {
        if let savedItems = defaults.stringArray(forKey: "stringArray"){
            for item in savedItems{
                item.hasPrefix(sender.text!){
                    print(item)
                    itemsaved.append(item)

                }
            }
        }
    }



    @IBAction func editingchanged(_ sender: UITextField) {
        self.picker.dataSource = self
        self.picker.delegate = self
        retreivedata(sender: self.searchTextField)
    }
}

0 个答案:

没有答案