如何通过视图设置默认的UITextField值确实加载

时间:2019-03-09 17:33:41

标签: ios swift viewdidload

我正在尝试从保存到结构的JSON数据中将默认值加载到文本字段。获取JSON数据的函数正在viewdidload中运行。我在viewdidlod下有代码,它返回nil值。测试我在IBAction下运行的代码,效果很好。如何在Viewdidload中使代码正确运行?

override func viewDidLoad() {
    super.viewDidLoad()

    setUpPicker(textField: lenderName, pickerView: lenderNamePicker, PickerViewDelegate: self, PickerViewDataSource: self)
    setUpPicker(textField: mortgageTerm, pickerView: mortgageTermPicker, PickerViewDelegate: self, PickerViewDataSource: self)

    SelectionFunctions.MortgageTermSelection()

    getRates (completion: { [weak self] in
        self?.lenderName.reloadInputViews()
    })

    DispatchQueue.main.async {
        let setupLender = Data.currentRateData.first(where: {$0.financialInstitution == "CIBC Mortgages"})
        let setupRate = setupLender?.fiveYear
        self.mortgageRate.text = setupRate?.percentage
        print(setupRate)
        print(setupLender)
        print(Data.currentRateData.first?.financialInstitution)
    }

    lenderName.text = "CIBC Mortgages"
    mortgageAmount.text = "$300,000.00"
    orginalStartDate.text = ""
    mortgageTerm.text = "5 Year"
    //mortgageRate.text = "3.89%"
    OrginalDiscount.text = "1.25%"
    cashback.text = "$2,000"

    lenderName.addDoneButton()
    mortgageAmount.addDoneButton()

    orginalStartDate.addDoneButton()
    mortgageTerm.addDoneButton()
    mortgageRate.addDoneButton()
    orginalStartDate.addDoneButton()
    cashback.addDoneButton()
    OrginalDiscount.addDoneButton()

    func setupDelegate(textField: UITextField){
        textField.delegate = self
    }

    setupDelegate(textField: mortgageAmount)
    setupDelegate(textField: mortgageRate)
    setupDelegate(textField: OrginalDiscount)
    setupDelegate(textField: cashback)


    DatePicker()
}

1 个答案:

答案 0 :(得分:1)

只需将DispatchQueue.main.async的使用移到getRates调用的完成块中即可。

getRates (completion: { [weak self] in
    self?.lenderName.reloadInputViews()

    DispatchQueue.main.async {
        let setupLender = Data.currentRateData.first(where: {$0.financialInstitution == "CIBC Mortgages"})
        let setupRate = setupLender?.fiveYear
        self.mortgageRate.text = setupRate?.percentage
        print(setupRate)
        print(setupLender)
        print(Data.currentRateData.first?.financialInstitution)
    }
})

我假设getRates调用是加载DispatchQueue.main.async块内正在使用的数据的对象。