后台线程中的config UI,然后分配回主线程

时间:2018-09-05 15:54:53

标签: ios swift multithreading

嗨,我是一个新的快速开发人员,我正在尝试找到一种方法来在后台线程中加载我所有的文本字段,然后使其在查看控制器出现之前返回主线程。

因为在我的viewcontroller中,我需要设置差不多20个文本字段,例如其样式,占位符等。因此,当我点击处理该vc的按钮时,viewcontroller会花费相当长的一段时间。

我知道我可以使用它在后台执行设置文本字段

DispatchQueue.global(qos: .userInteractive).async {
        <#code#>
    }

但是我不知道将这段代码放在哪里。我试图将其放在viewDidLoad中,但这似乎不起作用。


编辑:添加我的代码

import UIKit
import MaterialComponents.MaterialTextFields

class AddNewDataVC: UIViewController {

    //Outlet
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var saveNewDataBtn: UIButton!
    @IBOutlet weak var sowInfoInputsStackView: UIStackView!
    @IBOutlet weak var giltInfoInputsStackView: UIStackView!
    @IBOutlet weak var matingInfoInputsStackView: UIStackView!
    @IBOutlet weak var farrowInfoInputsStackView: UIStackView!
    @IBOutlet weak var vaccinTable: UITableView!

    @IBOutlet weak var pigTypeTextField: PickerTextField!
    @IBOutlet weak var genderTextField: PickerTextField!
    @IBOutlet weak var chipIDTextField: MDCTextField!
    @IBOutlet weak var breedTextField: MDCTextField!
    @IBOutlet weak var subBreedTextField: MDCTextField!
    @IBOutlet weak var dadIDTextField: MDCTextField!
    @IBOutlet weak var momIDTextField: MDCTextField!
    @IBOutlet weak var penIDTextField: MDCTextField!
    @IBOutlet weak var weightTextField: MDCTextField!
    @IBOutlet weak var parityTextField: MDCTextField!
    @IBOutlet weak var birthDateTextField: PickerTextField!
    @IBOutlet weak var weanDateTextField: PickerTextField!

    @IBOutlet weak var arrivalDateTextField: PickerTextField!
    @IBOutlet weak var herdEntryDateTextField: PickerTextField!
    @IBOutlet weak var startOffDutySowDateTextField: PickerTextField!
    @IBOutlet weak var semenFromBoarIDTextField: MDCTextField!
    @IBOutlet weak var technicianNameTextField: PickerTextField!
    @IBOutlet weak var matingDateTextField: PickerTextField!
    @IBOutlet weak var estimateBirthDateTextField: PickerTextField!
    @IBOutlet weak var realBirthDateTextField: PickerTextField!
    @IBOutlet weak var totalNumberOfNewBornsTextField: MDCTextField!
    @IBOutlet weak var totalNumberOfDeadNewBornsTextField: MDCTextField!
    @IBOutlet weak var averageWeightOfNewBornsTextField: MDCTextField!
    @IBOutlet weak var accoucheurNameTextField: MDCTextField!
    @IBOutlet weak var newBornDeathReason1TextField: MDCTextField!
    @IBOutlet weak var newBornDeathReason2TextField: MDCTextField!
    @IBOutlet weak var newBornDeathReason3TextField: MDCTextField!
    @IBOutlet weak var newBornCullReason1TextField: MDCTextField!
    @IBOutlet weak var newBornCullReason2TextField: MDCTextField!
    @IBOutlet weak var newBornCullReason3TextField: MDCTextField!

    //Properties
    var pigTypeController: MDCTextInputControllerUnderline?
    var genderController: MDCTextInputControllerUnderline?
    var chipIDController: MDCTextInputControllerUnderline?
    var breedController: MDCTextInputControllerUnderline?
    var subBreedController: MDCTextInputControllerUnderline?
    var dadIDController: MDCTextInputControllerUnderline?
    var momIDController: MDCTextInputControllerUnderline?
    var penIDController: MDCTextInputControllerUnderline?
    var weightController: MDCTextInputControllerUnderline?
    var parityController: MDCTextInputControllerUnderline?
    var birthDateController: MDCTextInputControllerUnderline?
    var weanDateController: MDCTextInputControllerUnderline?

    var arrivalDateController: MDCTextInputControllerUnderline?
    var herdEntryDateController: MDCTextInputControllerUnderline?
    var startOffDutySowDateController: MDCTextInputControllerUnderline?
    var semenFromBoarIDController: MDCTextInputControllerUnderline?
    var techicianNameController: MDCTextInputControllerUnderline?
    var matingDateController: MDCTextInputControllerUnderline?
    var estimateBirthDateController: MDCTextInputControllerUnderline?
    var realBirthDateController: MDCTextInputControllerUnderline?
    var totalNumberOfNewBornsController: MDCTextInputControllerUnderline?
    var totalNumberOfDeadNewBornsController: MDCTextInputControllerUnderline?
    var averageWeightOfNewBornsController: MDCTextInputControllerUnderline?
    var accoucheurNameController: MDCTextInputControllerUnderline?
    var newBornDeathReason1Controller: MDCTextInputControllerUnderline?
    var newBornDeathReason2Controller: MDCTextInputControllerUnderline?
    var newBornDeathReason3Controller: MDCTextInputControllerUnderline?
    var newBornCullReason1Controller: MDCTextInputControllerUnderline?
    var newBornCullReason2Controller: MDCTextInputControllerUnderline?
    var newBornCullReason3Controller: MDCTextInputControllerUnderline?

    var allTextFieldControllers = [MDCTextInputControllerUnderline]()
    var injectedVaccinArray = [[String : Any]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupTextFields()

        registerKeyboardNotifications()
        addGestureRecognizer()

        vaccinTable.dataSource = self
        vaccinTable.delegate = self

    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

    @IBAction func closeAddNewDataPopupBtnPressed(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func saveNewDataBtnPressed(_ sender: Any) {
    }

    @IBAction func addVaccinDataBtnPressed(_ sender: UIButton) {
        let getDestStoryboard = UIStoryboard(name: "AddNewData", bundle: nil)
        let popupVC = getDestStoryboard.instantiateViewController(withIdentifier: "addVaccinDataVC") as! AddVaccinInfoVC
        popupVC.popupDelegate = self
        self.present(popupVC, animated: true, completion: nil)
    }

}

extension AddNewDataVC {
    func setupTextFields() {
        pigTypeController = MDCTextInputControllerUnderline(textInput: pigTypeTextField)
        pigTypeTextField.delegate = self
        pigTypeTextField.addData(data: PIG_TYPES_ENUM.allValues)
        pigTypeController?.placeholderText = "Loại lợn"
        allTextFieldControllers.append(pigTypeController!)

        genderController = MDCTextInputControllerUnderline(textInput: genderTextField)
        genderTextField.delegate = self
        genderTextField.addData(data: GENDERS)
        genderController?.placeholderText = "Giới tính"
        allTextFieldControllers.append(genderController!)

        chipIDController = MDCTextInputControllerUnderline(textInput: chipIDTextField)
        chipIDTextField.delegate = self
        chipIDController?.placeholderText = "Số chip"
        allTextFieldControllers.append(chipIDController!)

        breedController = MDCTextInputControllerUnderline(textInput: breedTextField)
        breedTextField.delegate = self
        breedController?.placeholderText = "Giống"
        allTextFieldControllers.append(breedController!)

        subBreedController = MDCTextInputControllerUnderline(textInput: subBreedTextField)
        subBreedTextField.delegate = self
        subBreedController?.placeholderText = "Giống phụ"
        allTextFieldControllers.append(subBreedController!)

        dadIDController = MDCTextInputControllerUnderline(textInput: dadIDTextField)
        dadIDTextField.delegate = self
        dadIDController?.placeholderText = "Số chip bố mẹ"
        allTextFieldControllers.append(dadIDController!)

        momIDController = MDCTextInputControllerUnderline(textInput: momIDTextField)
        momIDTextField.delegate = self
        momIDController?.placeholderText = "Số chip mẹ"
        allTextFieldControllers.append(momIDController!)

        penIDController = MDCTextInputControllerUnderline(textInput: penIDTextField)
        penIDTextField.delegate = self
        penIDController?.placeholderText = "Số chuồng"
        allTextFieldControllers.append(penIDController!)

        weightController = MDCTextInputControllerUnderline(textInput: weightTextField)
        weightTextField.delegate = self
        weightController?.placeholderText = "Số kg"
        allTextFieldControllers.append(weightController!)

        parityController = MDCTextInputControllerUnderline(textInput: parityTextField)
        parityTextField.delegate = self
        parityController?.placeholderText = "Số lứa"
        allTextFieldControllers.append(parityController!)

        birthDateController = MDCTextInputControllerUnderline(textInput: birthDateTextField)
        birthDateTextField.delegate = self
        birthDateController?.placeholderText = "Ngày sinh"
        allTextFieldControllers.append(birthDateController!)

        weanDateController = MDCTextInputControllerUnderline(textInput: weanDateTextField)
        weanDateTextField.delegate = self
        weanDateController?.placeholderText = "Ngày cai sữa"
        allTextFieldControllers.append(weanDateController!)

        arrivalDateController = MDCTextInputControllerUnderline(textInput: arrivalDateTextField)
        arrivalDateTextField.delegate = self
        arrivalDateController?.placeholderText = "Ngày đến"
        allTextFieldControllers.append(arrivalDateController!)

        herdEntryDateController = MDCTextInputControllerUnderline(textInput: herdEntryDateTextField)
        herdEntryDateTextField.delegate = self
        herdEntryDateController?.placeholderText = "Ngày nhập đàn"
        allTextFieldControllers.append(herdEntryDateController!)

        startOffDutySowDateController = MDCTextInputControllerUnderline(textInput: startOffDutySowDateTextField)
        startOffDutySowDateTextField.delegate = self
        startOffDutySowDateController?.placeholderText = "Ngày nái nghỉ"
        allTextFieldControllers.append(startOffDutySowDateController!)

        semenFromBoarIDController = MDCTextInputControllerUnderline(textInput: semenFromBoarIDTextField)
        semenFromBoarIDTextField.delegate = self
        semenFromBoarIDController?.placeholderText = "Mã heo nọc"
        allTextFieldControllers.append(semenFromBoarIDController!)

        techicianNameController = MDCTextInputControllerUnderline(textInput: technicianNameTextField)
        technicianNameTextField.delegate = self
        techicianNameController?.placeholderText = "Người phối"
        technicianNameTextField.addData(data: TECHNICIAN_NAMES)
        allTextFieldControllers.append(techicianNameController!)

        matingDateController = MDCTextInputControllerUnderline(textInput: matingDateTextField)
        matingDateTextField.delegate = self
        matingDateController?.placeholderText = "Ngày phối"
        allTextFieldControllers.append(matingDateController!)

        estimateBirthDateController = MDCTextInputControllerUnderline(textInput: estimateBirthDateTextField)
        estimateBirthDateTextField.delegate = self
        estimateBirthDateController?.placeholderText = "Ngày đẻ dự kiến"
        allTextFieldControllers.append(estimateBirthDateController!)

        realBirthDateController = MDCTextInputControllerUnderline(textInput: realBirthDateTextField)
        realBirthDateTextField.delegate = self
        realBirthDateController?.placeholderText = "Ngày đẻ thực tế"
        allTextFieldControllers.append(realBirthDateController!)

        totalNumberOfNewBornsController = MDCTextInputControllerUnderline(textInput: totalNumberOfNewBornsTextField)
        totalNumberOfNewBornsTextField.delegate = self
        totalNumberOfNewBornsController?.placeholderText = "Tổng heo con sinh"
        allTextFieldControllers.append(totalNumberOfNewBornsController!)

        totalNumberOfDeadNewBornsController = MDCTextInputControllerUnderline(textInput: totalNumberOfDeadNewBornsTextField)
        totalNumberOfDeadNewBornsTextField.delegate = self
        totalNumberOfDeadNewBornsController?.placeholderText = "Tổng heo con chết"
        allTextFieldControllers.append(totalNumberOfDeadNewBornsController!)

        averageWeightOfNewBornsController = MDCTextInputControllerUnderline(textInput: averageWeightOfNewBornsTextField)
        averageWeightOfNewBornsTextField.delegate = self
        averageWeightOfNewBornsController?.placeholderText = "Kg trung bình"
        allTextFieldControllers.append(averageWeightOfNewBornsController!)

        accoucheurNameController = MDCTextInputControllerUnderline(textInput: accoucheurNameTextField)
        accoucheurNameTextField.delegate = self
        accoucheurNameController?.placeholderText = "Người đỡ đẻ"
        allTextFieldControllers.append(accoucheurNameController!)

        newBornDeathReason1Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason1TextField)
        newBornDeathReason1TextField.delegate = self
        newBornDeathReason1Controller?.placeholderText = "Chết khô"
        allTextFieldControllers.append(newBornDeathReason1Controller!)

        newBornDeathReason2Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason2TextField)
        newBornDeathReason2TextField.delegate = self
        newBornDeathReason2Controller?.placeholderText = "Chết lưu"
        allTextFieldControllers.append(newBornDeathReason2Controller!)

        newBornDeathReason3Controller = MDCTextInputControllerUnderline(textInput: newBornDeathReason3TextField)
        newBornDeathReason3TextField.delegate = self
        newBornDeathReason3Controller?.placeholderText = "Chết tươi"
        allTextFieldControllers.append(newBornDeathReason3Controller!)

        newBornCullReason1Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason1TextField)
        newBornCullReason1TextField.delegate = self
        newBornCullReason1Controller?.placeholderText = "Loại nhỏ"
        allTextFieldControllers.append(newBornCullReason1Controller!)

        newBornCullReason2Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason2TextField)
        newBornCullReason2TextField.delegate = self
        newBornCullReason2Controller?.placeholderText = "Loại yếu"
        allTextFieldControllers.append(newBornCullReason2Controller!)

        newBornCullReason3Controller = MDCTextInputControllerUnderline(textInput: newBornCullReason3TextField)
        newBornCullReason3TextField.delegate = self
        newBornCullReason3Controller?.placeholderText = "Loại nhỏ"
        allTextFieldControllers.append(newBornCullReason3Controller!)

        for controller in allTextFieldControllers {
            controller.activeColor = Theme.darkAccent
            controller.floatingPlaceholderActiveColor = Theme.darkAccent
        }
    }

    func addGestureRecognizer() {
        let tapRecognizer = UITapGestureRecognizer(target: self,
                                                   action: #selector(tapDidTouch(sender: )))
        self.scrollView.addGestureRecognizer(tapRecognizer)
    }

    @objc func tapDidTouch(sender: Any) {
        self.view.endEditing(true)
    }

    func registerKeyboardNotifications() {
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(
            self,
            selector: #selector(keyboardWillShow(notif:)),
            name: .UIKeyboardWillChangeFrame,
            object: nil)
        notificationCenter.addObserver(
            self,
            selector: #selector(keyboardWillShow(notif:)),
            name: .UIKeyboardWillShow,
            object: nil)
        notificationCenter.addObserver(
            self,
            selector: #selector(keyboardWillHide(notif:)),
            name: .UIKeyboardWillHide,
            object: nil)
    }

    @objc func keyboardWillShow(notif: Notification) {
        guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        scrollView.contentInset = UIEdgeInsets(top: 0.0,
                                               left: 0.0,
                                               bottom: frame.height,
                                               right: 0.0)
    }

    @objc func keyboardWillHide(notif: Notification) {
        scrollView.contentInset = UIEdgeInsets()
    }

    func toggleFarrowInfoInputsStackView(toggle: Bool) {
        if toggle {
            sowInfoInputsStackView.isHidden = false
        } else {
            sowInfoInputsStackView.isHidden = true
        }
    }

    func toggleGiltInputs(toggle: Bool) {
        if toggle {
            giltInfoInputsStackView.isHidden = false
        } else {
            giltInfoInputsStackView.isHidden = true
        }
    }

    func toggleOffDutySowInputs(toggle: Bool) {
        if toggle {
            startOffDutySowDateTextField.isHidden = false
        } else {
            startOffDutySowDateTextField.isHidden = true
        }
    }

    func toggleMatingInputs(toggle: Bool) {
        if toggle {
            matingInfoInputsStackView.isHidden = false
        } else {
            matingInfoInputsStackView.isHidden = true
        }
    }

    func toggleFarrowInputs(toggle: Bool) {
        if toggle {
            farrowInfoInputsStackView.isHidden = false
        } else {
            farrowInfoInputsStackView.isHidden = true
        }
    }

    func toggleParityTextField(toggle: Bool) {
        if toggle {
            parityTextField.isHidden = false
        } else {
            parityTextField.isHidden = true
        }
    }
}

extension AddNewDataVC: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.resignFirstResponder()
        return false
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if let textField = textField as? PickerTextField {
            let text = textField.text?.lowercased()
            if !textField.isDatePicker && textField == pigTypeTextField {
                if text!.contains("nái") || textField.text! == PIG_TYPES_ENUM.gilt.rawValue {
                    toggleFarrowInfoInputsStackView(toggle: true)
                    if textField.text! == PIG_TYPES_ENUM.gilt.rawValue {
                        toggleGiltInputs(toggle: true)
                        toggleOffDutySowInputs(toggle: false)
                        toggleMatingInputs(toggle: false)
                        toggleFarrowInputs(toggle: false)
                    } else if textField.text! == PIG_TYPES_ENUM.offDutySow.rawValue {
                        toggleGiltInputs(toggle: true)
                        toggleOffDutySowInputs(toggle: true)
                        toggleMatingInputs(toggle: false)
                        toggleFarrowInputs(toggle: false)
                    } else if textField.text! == PIG_TYPES_ENUM.matingSow.rawValue {
                        toggleGiltInputs(toggle: true)
                        toggleOffDutySowInputs(toggle: false)
                        toggleMatingInputs(toggle: true)
                        toggleFarrowInputs(toggle: false)
                    } else if textField.text! == PIG_TYPES_ENUM.farrow.rawValue {
                        toggleGiltInputs(toggle: true)
                        toggleOffDutySowInputs(toggle: false)
                        toggleMatingInputs(toggle: true)
                        toggleFarrowInputs(toggle: true)
                    }
                } else {
                    toggleFarrowInfoInputsStackView(toggle: false)
                    toggleGiltInputs(toggle: false)
                    toggleOffDutySowInputs(toggle: false)
                    toggleMatingInputs(toggle: false)
                    toggleFarrowInputs(toggle: false)
                    if textField.text! == PIG_TYPES_ENUM.boar.rawValue {
                        genderTextField.text = "Đực"
                        genderTextField.isUserInteractionEnabled = false
                    } else {
                        genderTextField.text = ""
                        genderTextField.isUserInteractionEnabled = true
                    }
                }
            } else if !textField.isDatePicker && textField == genderTextField {
                if textField.text == "Cái" {
                    toggleParityTextField(toggle: true)
                } else {
                    toggleParityTextField(toggle: false)
                }
            }
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool  {
        if textField is PickerTextField {
            textField.resignFirstResponder()
            return false
        } else {
            return true
        }
    }
}

extension AddNewDataVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return injectedVaccinArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = vaccinTable.dequeueReusableCell(withIdentifier: "injectedVaccinCell", for: indexPath) as? InjectedVaccinCell else {
            return UITableViewCell()
        }
        cell.configureCell(value: injectedVaccinArray[indexPath.row])
        return cell
    }
}

extension AddNewDataVC: PopupDelegates {
    func popupValueSelected(value: [String : Any]) {
        self.injectedVaccinArray.append(value)
        self.vaccinTable.reloadData()
    }
}

我知道还有很多改进的余地,但是我只是学得很快,所以很抱歉,如果我的代码使您发痒哈哈。现在,我只是专注于使其工作,并将稍后尝试对其进行清理。

0 个答案:

没有答案