选择器视图不选择第一个对象

问题描述 投票:0回答:3

我的代码现在有一个选择器视图,可以在文本字段上放置一个单词。问题是用户必须更改选择器视图上的单词才能工作。我在照片下方添加了更多信息。

import UIKit

class ViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet var tx: UITextField!

    let animals = ["lion", "Dog","JUDO"]
    var pickerview = UIPickerView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib

        pickerview.delegate = self
        pickerview.dataSource = self
        tx.inputView = pickerview
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: view.bounds.width, height: 44))

        var items = [UIBarButtonItem]()


        items.append( UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAction)) )
        toolbar.items = items
        tx.inputAccessoryView = toolbar
    }
    @objc func doneAction(){

        tx.resignFirstResponder()
        view.endEditing(true)

    }
    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return animals.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return  animals[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        tx.text = animals[row]

    }
}

picker view with default value selected; text field is empty

如果我点击完成按钮,则不会传输任何内容。我必须从“狮子”向下滚动到“狗”,然后回到“狮子”以换取“狮子”。我只想点击完成按钮并转移“狮子”。

ios select button uipickerview swift4
3个回答
0
投票

选择器视图的值最初不会更改。您应该将数组的第一个元素作为viewDidLoad中文本字段的文本。

override func viewDidLoad() {
    [...]

    tx.text = animals.first
}

0
投票

如果你想点击完成按钮获得选择器的值,你应该使用pickerview.selectedRow(inComponent: 0)来获取选择器视图中选择的当前值。如果您在不滚动的情况下打开并关闭选择器,则不会调用func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)。所以你的代码需要改变如下

@objc func doneAction(){

        let selectedIndex = pickerview.selectedRow(inComponent: 0)
        tx.text = animals[selectedIndex]
        tx.resignFirstResponder()
        view.endEditing(true)

    }

-1
投票

尝试以下解决方案

 @objc func doneAction(){

    tx.resignFirstResponder()

    // get first index value of array if tx is empty
    if (tx.text?.isEmpty)! {
       tx.text = self.animals.first
    }

    view.endEditing(true)

}
© www.soinside.com 2019 - 2024. All rights reserved.