gpt4 book ai didi

ios - 当我将 PickerView 与 textField 一起使用时隐藏键盘

转载 作者:行者123 更新时间:2023-12-01 18:41:04 24 4
gpt4 key购买 nike

我想实现一个简单的应用程序,但我遇到了一些麻烦。我添加了 textField 和 PickerView。当我在 textField 上进行选项卡时,出现了 PickerView。但是标准键盘也出现了(我不想要它)。当我再次在 textField 上进行选项卡时,PickerView 不会出现。我怎样才能收到这个问题?非常感谢!

这是我的代码:

    import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

@IBOutlet weak var pickerView1: UIPickerView!
@IBOutlet weak var textField1: UITextField!

var age = ["8", "18", "28", "38", "48"]

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

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == pickerView1 {
}
return age[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerView1 {
self.textField1.text = self.age[row]
self.pickerView1.isHidden = true
}
}

func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.textField1 {
self.pickerView1.isHidden = false
}
}

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

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

最佳答案

为什么你不尝试简单的方法,只需将你的选择器 View 添加为你的文本字段的输入 View

 textField1.inputView = pickerView1

This will not give you a direct way to dismiss the view since your UIPickerView has no return button, which is why I recommend to use the inputAccessoryView property to display a toolbar with a done button


  let myToolbar = UIToolbar(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(320), height: CGFloat(44)))
//should code with variables to support view resizing
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.inputAccessoryViewDidFinish))
//using default text field delegate method here, here you could call
//myTextField.resignFirstResponder to dismiss the views
myToolbar.setItems([doneButton], animated: false)
lblcurrentText.inputAccessoryView = myToolbar

并将函数称为
    func inputAccessoryViewDidFinish() {
lblcurrentText.resignFirstResponder()
}

同时在您的pickerview上选择后隐藏文本字段,如
 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerView1 {
self.textField1.text = self.age[row]
self.inputAccessoryViewDidFinish()
}
}

教程

例如,您可以在 here 中获得分步教程。

关于ios - 当我将 PickerView 与 textField 一起使用时隐藏键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com