简体   繁体   English

触摸 UITextField 时设置 UIPickerView 的默认值

[英]Set default value of UIPickerView when UITextField is touched

I want to keep the same placeholder text in my UITextField which is "Location".我想在我的 UITextField 中保留相同的占位符文本,即“位置”。 Once the UITextField is touched then I want the first value of the UIPickerView to be displayed.触摸 UITextField 后,我希望显示 UIPickerView 的第一个值。 The way it is now the user has to scroll down then back up for the value to be displayed in the UITextField.现在的方式是用户必须向下滚动然后再向上滚动以在 UITextField 中显示值。 I want the value to be displayed in the UITextField as soon as the UIPickerView is open.我希望在 UIPickerView 打开后立即在 UITextField 中显示该值。 unselected, selected-UITextField still shows no value未选中,选中的 UITextField 仍然没有显示任何值

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]
}

Implement the textFieldDidBeginEditing text field delegate method and set the text field's text if it doesn't already have a value.实现textFieldDidBeginEditing文本字段委托方法并设置文本字段的文本(如果它还没有值)。

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

I'm going to build on rmaddy's answer and add more nuances and answers to questions in the comments.我将建立在 rmaddy 的回答基础上,并在评论中添加更多细微差别和问题的答案。

Main answer lays in the first extension, the rest of the code outlines class structure and components that need to be present for everything to work.主要答案在于第一个扩展,其余代码概述了类结构和组件,它们需要存在才能使一切正常工作。

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
    //...
}
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


    }

}
@IBOutlet weak var tF: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    tF.delegate = self
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM