本文介绍了在 UIPickerView 中重新加载数据和组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重新加载 UIPickerView,因为当我选择例如选择 PickerView 的第二项时,在第二个 PickerView 选择选择器的位置时不会回到首先,数据没有完全重新加载,所以我试试这个:

I'm trying to reload UIPickerView, because, when I chose select for exemple the secon item of a PickerView, at the second PickerView choosing the placement of the selector don't get back to the first, and the data isn't reloaded perfectly, so I try this:

NSNotificationCenter.defaultCenter().addObserver(self, selector: ("updatePicker"), name: UITextFieldTextDidBeginEditingNotification, object: nil)

func updatePicker(){
  self.pickerView.reloadAllComponents()
}

但我收到一个错误:

致命错误:解包可选值时意外发现 nil

完整代码:

import UIKit

@objc
protocol DemandeGratuiteViewControllerDelegate {
    optional func toggleLeftPanel()
    optional func collapseSidePanels()
}

class DemandeGratuiteViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource , UITextFieldDelegate {

    var delegate: DemandeGratuiteViewControllerDelegate?

    @IBOutlet var tfProjet: UITextField!
    @IBOutlet var tfLogement: UITextField!
    @IBOutlet var libelleValeurActuelleDuBien: UILabel!
    @IBOutlet var libelleLoyer: UILabel!
    @IBOutlet var tfValeurActuelleBien: UITextField!
    @IBOutlet var tfLoyer: UITextField!
    @IBOutlet var tfProfession: UITextField!
    @IBOutlet var tfContrat: UITextField!
    @IBOutlet var pickerView: UIPickerView!
    @IBOutlet weak var RevenusNetsConstraint: NSLayoutConstraint!
    @IBOutlet weak var libelleDeclare: UILabel!

    var pvProjetData = ["-Choisir-", "Rachat de crédits", "Renégociation de crédits"]
    var pvLogement = ["-Choisir-", "Propriétaire", "Locataire", "Logement de fonction", "Hébérgé par un tiers", "Hébérgé poar la famille"]
    var pvProfession = ["-Choisir-", "Agriculteur exploitant", "Artisan, commercant", "Cadre", "Chef d'entreprise", "Fonctionnaire", "Intérimaire", "Ouvrier", "Retraité", "Salarié", "Sans emploi"]
    var pvContrat1 = ["-Choisir-", "Profession libérale"]
    var pvContrat2 = ["-Choisir-", "CDI", "CDD", "Stagiaire"]
    var pvContrat3 = ["-Choisir-", "Stagiaire", "Titulaire", "Contractuelle"]
    var pvContrat4 = ["Intérimaire"]
    var pvContrat5 = ["Retraité"]
    var pvContrat6 = ["Sans contrat"]
    var pvFichage = ["-Choisir-", "Non", "Interdit bancaire", "FICP", "Les deux"]
    var pvDureeRemb12 = ["-Choisir-", "5", "6", "7", "8", "9", "10", "11", "12"]
    var pvDureeRemb25 = ["-Choisir", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25"]
    var pvSituationFamille = ["-Choisir", "Marié(e)", "Célibataire", "Veuf(ve)", "Divorcé(e)", "Pacsé(e)", "Union libre", "En instance de divorce"]
    var pvNombreEnfants = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    var pvCivilite = ["--", "M", "Mme", "Mlle"]


    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 38.0/255.0, green: 51.0/255.0, blue: 85.0/255.0, alpha: 1.0)
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Gotham", size: 13)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
        self.title = "DEMANDE GRATUITE"
        NSNotificationCenter.defaultCenter().addObserver(self, selector: ("updatePicker"), name: UITextFieldTextDidBeginEditingNotification, object: nil)

        let pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 100))


        pickerView.showsSelectionIndicator = true
        pickerView.delegate = self
        pickerView.dataSource = self

        tfProjet.inputView = pickerView
        tfLogement.inputView = pickerView
        tfProfession.inputView = pickerView
        tfContrat.inputView = pickerView


        RevenusNetsConstraint.priority = 999
        libelleLoyer.hidden = true
        libelleValeurActuelleDuBien.hidden = true
        tfLoyer.hidden = true
        tfValeurActuelleBien.hidden = true


        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:"))
    }

    func tfLogementDidChange(){
        if(tfLogement.text == "Propriétaire"){
            RevenusNetsConstraint.priority = 994
            libelleValeurActuelleDuBien.hidden = false
            tfValeurActuelleBien.hidden = false
            tfLoyer.hidden = true
            libelleLoyer.hidden = true
        }
        else if (tfLogement.text == "Locataire"){
            RevenusNetsConstraint.priority = 994
            libelleValeurActuelleDuBien.hidden = true
            tfValeurActuelleBien.hidden = true
            tfLoyer.hidden = false
            libelleLoyer.hidden = false
        }
        else{
            RevenusNetsConstraint.priority = 999
            libelleLoyer.hidden = true
            libelleValeurActuelleDuBien.hidden = true
            tfLoyer.hidden = true
            tfValeurActuelleBien.hidden = true
        }
    }

    func handleTap(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
            view.endEditing(true)
        }
        sender.cancelsTouchesInView = false
    }


    @IBAction func menuTapped(sender: AnyObject) {
        print(delegate)
        delegate?.toggleLeftPanel?()
    }


    // returns the number of 'columns' to display.
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1
    }

    //////////

    func updatePicker(){
        self.pickerView!.reloadAllComponents()
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if tfProjet.isFirstResponder(){
            return pvProjetData.count
        }else if tfLogement.isFirstResponder(){
            return pvLogement.count
        }else if tfProfession.isFirstResponder(){
            return pvProfession.count
        }else if tfContrat.isFirstResponder(){
            if tfProfession.text == "Agriculteur exploitant"{
                return pvContrat1.count
            }
            else if tfProfession.text == "Artisan, commercant"{
                return pvContrat2.count
            }
        }
        return 1
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if tfProjet.isFirstResponder(){
            return pvProjetData[row]
        }else if tfLogement.isFirstResponder(){
            return pvLogement[row]
        }else if tfProfession.isFirstResponder(){
            return pvProfession[row]
        }else if tfContrat.isFirstResponder(){
            if tfProfession.text == "Agriculteur exploitant"{
                return pvContrat1[row]
            }
            else if tfProfession.text == "Artisan, commercant"{
                return pvContrat2[row]
            }
        }
        // continue this way and implement all cases
        return ""
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if tfProjet.isFirstResponder(){
            let itemselected = pvProjetData[row]
            tfProjet.text = itemselected
            self.tfProjet.endEditing(true)
        }else if tfLogement.isFirstResponder(){
            let itemselected = pvLogement[row]
            tfLogement.text = itemselected
            self.tfLogement.endEditing(true)
            tfLogementDidChange()
        }else if tfProfession.isFirstResponder(){
            let itemselected = pvProfession[row]
            tfProfession.text = itemselected
            self.tfProfession.endEditing(true)
        }else if tfContrat.isFirstResponder(){
            if tfProfession.text == "Agriculteur exploitant"{
                let itemselected = pvContrat1[row]
                tfContrat.text = itemselected
                self.tfContrat.endEditing(true)
            }
            else if tfProfession.text == "Artisan, commercant"{
                let itemselected = pvContrat2[row]
                tfContrat.text = itemselected
                self.tfContrat.endEditing(true)
            }
        }
    }

推荐答案

好的,使用评论中的信息 - 特别是这个(重点是我的):

Ok, with the information from the comments - specifically this (emphasis mine):

@Losiowaty 我明白你的意思,在我的StoryBoard 并连接它,但为什么我有 PickerView 即使 我没有在我的 StoryBoard 上放一个 UIPicerView

选择器视图的 @IBOutlet 具有误导性.根据以上信息,问题似乎是您从未分配给 self.pickerView.在 viewDidLoad 你有这个代码:

The @IBOutlet for the picker view was misleading. With the above information, it seems that the issue is that you never assign to self.pickerView. In viewDidLoad you have this code :

let pickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 100))
pickerView.showsSelectionIndicator = true
pickerView.delegate = self
pickerView.dataSource = self

只需在下面添加 self.pickerView = pickerView 就可以了.

Simply add self.pickerView = pickerView below this and everything should be fine.

请注意,当您以编程方式创建视图时,您不需要也不应该将它们注释为 @IBOutlets.它降低了代码对其他人的可读性,甚至可能在一段时间后对您来说也是如此.IBOutlet 代表 Interface Builder Outlet.

Note, that when you create views programatically you don't need and shouldn't annotate them as @IBOutlets. It makes the code less readable for someone else, and maybe even for you after some time. IBOutlet stands for Interface Builder Outlet.

这篇关于在 UIPickerView 中重新加载数据和组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 23:54