触摸 UITextField 时设置 UIPickerView 的默认值

Posted

技术标签:

【中文标题】触摸 UITextField 时设置 UIPickerView 的默认值【英文标题】:Set default value of UIPickerView when UITextField is touched 【发布时间】:2018-05-23 03:30:56 【问题描述】:

我想在我的 UITextField 中保留相同的占位符文本,即“位置”。触摸 UITextField 后,我希望显示 UIPickerView 的第一个值。现在的方式是用户必须向下滚动然后再向上滚动才能在 UITextField 中显示该值。我希望 UIPickerView 打开后立即在 UITextField 中显示该值。 unselected,selected-UITextField still shows no value

override func viewDidLoad() 
    let thePicker = UIPickerView()
    thePicker.delegate = self
    location.inputView = thePicker
    thePicker.selectRow(1, inComponent: 0, animated: true)


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


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


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
    return pickOptions[row]



func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
    location.text = pickOptions[row]

【问题讨论】:

【参考方案1】:

实现textFieldDidBeginEditing 文本字段委托方法并设置文本字段的文本(如果它还没有值)。

func textFieldDidBeginEditing(_ textField: UITextField) 
    if textField.text!.isEmpty 
        // set the text as needed
    

【讨论】:

我添加了这个,但它没有被调用,我尝试了一个打印语句并且打印语句也没有显示在控制台中。不知道我错过了什么。文本字段肯定是空的 您是否设置了文本字段的委托?另外,将? 更改为!(在这种情况下是安全的)。【参考方案2】:

我将在 rmaddy 的答案的基础上,为 cmets 中的问题添加更多细微差别和答案。

主要答案在于第一个扩展,其余代码概述了类结构和所有工作都需要存在的组件。

class ViewController 
    private var selectedItem: String = ""
    private let pickerList = [
        "First item",
        "Second item",
        "Third item"
    ]
     override func viewDidLoad() 
        super.viewDidLoad()
        pickerTextField.delegate = self
        //...
        // Layout setup
        //...
    
    private let pickerTextField: UITextField = 
        let textField = UITextField()
        textField.tintColor = .clear // hides cursor
        return textField
    ()
    //...
    // UI Elements including picker
    //...


extension ViewController: UITextFieldDelegate 
    internal func textFieldDidBeginEditing(_ textField: UITextField) 
        if textField == pickerTextField, let textFieldText = textField.text, textFieldText.isEmpty 
            pickerTextField.text = pickerList.first   // fills textfield before any selection is made
        
    


extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource 
    //...
    // PickerView delegate methods
    //...

【讨论】:

【参考方案3】:
import UIKit

class ActivityPersonDetail : UIViewController,UITextFieldDelegate,UIPickerViewDataSource, UIPickerViewDelegate 


    let salutations = ["1", "2", "3","4","5","6","7","8","9","10","11","12"]

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

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
        return salutations[row]
    

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
        pickerTF.text = salutations[row]
        picker.isHidden = true

    

    func textFieldDidBeginEditing(_ textField: UITextField) 

        if textField == self.pickerTF 
            picker.isHidden = false
            textField.endEditing(true)
        
    


    lazy var picker: UIPickerView = 
        let pickerView = UIPickerView()
        pickerView.delegate = self
        pickerView.translatesAutoresizingMaskIntoConstraints = false
        pickerView.backgroundColor = .white

        pickerTF.inputView = pickerView
        return pickerView
    ()

    let  arrowImage: UIImageView = 

        let image = UIImageView()
        image.translatesAutoresizingMaskIntoConstraints = false
        image.image = #imageLiteral(resourceName: "down_arrow")
        image.contentMode = .scaleAspectFit
        return image
     ()

    lazy var pickerTF: UITextField = 

        let tf = UITextField()
        tf.delegate = self
        tf.translatesAutoresizingMaskIntoConstraints = false
        tf.textColor = .black
        tf.font = .systemFont(ofSize: 24, weight: .medium)
        tf.placeholder = salutations[0]
        return tf
    ()



    //
    // MARK :- viewDidLoad ============================================================================
    //
    private var pickerView: UIPickerView!

    override func viewDidLoad() 

        super .viewDidLoad()
        view.backgroundColor = .white

        setupNavigationBar()
        setupViews()
        setupAutoLayout()

    

    // ================ setupNavigationBar =============

    func setupNavigationBar()

        title = ""
        hideBackTitle()
        navigationController?.navigationBar.barTintColor = .navBar

    
    func hideBackTitle() 
        let backbarItem = UIBarButtonItem()
        backbarItem.title = ""
        navigationItem.backBarButtonItem = backbarItem
    


    // ================ setupViews =============

    func setupViews()

        view.addSubview(pickerTF)
        pickerTF.addSubview(arrowImage)
        view.addSubview(picker)
        picker.isHidden = true
    


    // ================ setupAutoLayout =============

    func setupAutoLayout() 

        pickerTF.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 80).isActive = true
        pickerTF.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true
        pickerTF.heightAnchor.constraint(equalToConstant: 60).isActive = true
        pickerTF.widthAnchor.constraint(equalToConstant: 70).isActive = true

        arrowImage.rightAnchor.constraint(equalTo: pickerTF.rightAnchor, constant: -15).isActive = true
        arrowImage.topAnchor.constraint(equalTo: pickerTF.topAnchor, constant: 16).isActive = true
        arrowImage.widthAnchor.constraint(equalToConstant: 22).isActive = true
        arrowImage.heightAnchor.constraint(equalToConstant: 22).isActive = true

        picker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        picker.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        picker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        picker.heightAnchor.constraint(equalToConstant: 100).isActive = true


    


【讨论】:

【参考方案4】:
@IBOutlet weak var tF: UITextField!

override func viewDidLoad() 
    super.viewDidLoad()

    tF.delegate = self


func textFieldDidEndEditing(_ textField: UITextField) 
    textField.text = pickOptions[row]

【讨论】:

以上是关于触摸 UITextField 时设置 UIPickerView 的默认值的主要内容,如果未能解决你的问题,请参考以下文章

UITextField 是不是消耗触摸事件?

触摸时 UITextField 崩溃

iOS - 在 UITextField 之外触摸时关闭键盘

UITextField 添加到 UIView 时不响应触摸事件

UIImageView 的 UITextField 子视图没有响应触摸事件

UITextField 触摸事件在 UIScrollView 中不起作用