我的代码现在有一个选择器视图,可以在文本字段上放置一个单词。问题是用户必须更改选择器视图上的单词才能工作。我在照片下方添加了更多信息。
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]
}
}
如果我点击完成按钮,则不会传输任何内容。我必须从“狮子”向下滚动到“狗”,然后回到“狮子”以换取“狮子”。我只想点击完成按钮并让“狮子”转移。
答案 0 :(得分:0)
选择器视图的值最初不会更改。您应该将数组的第一个元素作为tab[, colSums(is.na(tab)) <= 10500/2]
中文本字段的文本。
viewDidLoad
答案 1 :(得分: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)
}
答案 2 :(得分:-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)
}