Как установить UIPickerView выбранное значение из Realm? - PullRequest
0 голосов
/ 03 февраля 2020

Я установил viewcontroller, где есть 7 «вопросов» и 7 «ответов». Я создал UIPickerView, который позволяет пользователям выбирать свой ответ, когда они нажимают на UITextField ответа, и сохранять его в области.

Однако, когда пользователь уже выбрал ответ (например, «Согласен»), «Согласен» не отображается как выбранная строка в UIPickerView, когда я щелкаю UITextField для этого ответа.

Как установить значение по умолчанию или «selectedrow» для UIPickerview для ответа, отображаемого в UITextField и сохраненного в Realm?

import UIKit
import RealmSwift

class QuestionViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupDelegateForPickerView()
        setupDelegatesForTextFields()
    }

    override func viewWillAppear(_ animated: Bool) {
        loadAnswers()
    }

    @IBOutlet weak var Question1TextField: UITextField!

    @IBOutlet weak var Question2TextField: UITextField!

    @IBOutlet weak var Question3TextField: UITextField!

    @IBOutlet weak var Question4TextField: UITextField!

    @IBOutlet weak var Question5TextField: UITextField!

    @IBOutlet weak var Question6TextField: UITextField!

    @IBOutlet weak var Question7TextField: UITextField!

    // Setting up a UIPickerview from the ToolbarPickerView class

    let realm = try! Realm()

    var answers: Results<Answer>?

    var answerArray = [UITextField]()

    func loadAnswers() {
        var answersGiven = realm.objects(Answer.self).filter("id = 1")
        for answer in answersGiven {
            Question1TextField.text = answer.Answer1
            Question2TextField.text = answer.Answer2
            Question3TextField.text = answer.Answer3
            Question4TextField.text = answer.Answer4
            Question5TextField.text = answer.Answer5
            Question6TextField.text = answer.Answer6
            Question7TextField.text = answer.Answer7
        }
    }

    let pickerView = ToolbarPickerView()

    let Menu = ["Strongly Disagree",
                "Disagree",
                "Neutral",
                "Agree",
                "Strongly Agree"]

    var selectedMenu : String?

    func setupDelegatesForTextFields() {
        //appending textfields in an array
        answerArray += [Question1TextField, Question2TextField, Question3TextField, Question4TextField, Question5TextField, Question6TextField, Question7TextField]
        //using the array to set up the delegates, inputview for pickerview and also the inputAccessoryView for the toolbar
        for answer in answerArray {
            answer.delegate = self
            answer.inputView = pickerView
            answer.inputAccessoryView = pickerView.toolbar
        }
    }

    func setupDelegateForPickerView() {
        pickerView.dataSource = self
        pickerView.delegate = self
        pickerView.toolbarDelegate = self
    }

    func setDefaultValue(item: String, inComponent: Int){
     if let indexPosition = Menu.firstIndex(of: item){
       pickerView.selectRow(indexPosition, inComponent: inComponent, animated: true)
     }
    }

        // Dismissing Keyboard on tapped
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.view.endEditing(true)
        }
    }

extension QuestionViewController : UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.pickerView.reloadAllComponents()
    }
}

extension QuestionViewController : UIPickerViewDelegate, UIPickerViewDataSource {
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.Menu.count
    }

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.Menu[row]
    }


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

        let answer = Answer()
        answer.id = 1


        // Check if the textfield isFirstResponder.
        if Question1TextField.isFirstResponder {
            Question1TextField.text = self.Menu[row]
            answer.Answer1 = Question1TextField.text

            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer1": self.Menu[row]], update: .modified)
            }
        } else if Question2TextField.isFirstResponder {
            Question2TextField.text = self.Menu[row]
            answer.Answer2 = Question2TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer2": self.Menu[row]], update: .modified)
            }
        } else if Question3TextField.isFirstResponder {
            Question3TextField.text = self.Menu[row]
            answer.Answer3 = Question3TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer3": self.Menu[row]], update: .modified)
            }
        } else if Question4TextField.isFirstResponder {
            Question4TextField.text = self.Menu[row]
            answer.Answer4 = Question4TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer4": self.Menu[row]], update: .modified)
            }
        } else if Question5TextField.isFirstResponder {
            Question5TextField.text = self.Menu[row]
            answer.Answer5 = Question5TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer5": self.Menu[row]], update: .modified)
            }
        } else if Question6TextField.isFirstResponder {
            Question6TextField.text = self.Menu[row]
            answer.Answer6 = Question6TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer6": self.Menu[row]], update: .modified)
            }
        } else if Question7TextField.isFirstResponder {
            Question7TextField.text = self.Menu[row]
            answer.Answer7 = Question7TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer7": self.Menu[row]], update: .modified)
            }
        } else {
        //log errors
        }
    }
}

extension QuestionViewController: ToolbarPickerViewDelegate {

    func didTapDone() {
      let row = self.pickerView.selectedRow(inComponent: 0)
      self.pickerView.selectRow(row, inComponent: 0, animated: false)
      selectedMenu = self.Menu[row]
        self.view.endEditing(true)
    }

    func didTapCancel() {
       self.view.endEditing(true)
    }
}

Вот класс инструментов на панели инструментов, просто добавьте .


import UIKit

protocol ToolbarPickerViewDelegate: class {
    func didTapDone()
    func didTapCancel()
}

class ToolbarPickerView: UIPickerView {

    public private(set) var toolbar: UIToolbar?
    public weak var toolbarDelegate: ToolbarPickerViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit() {
        let toolBar = UIToolbar()
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneTapped))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelTapped))

        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true

        toolBar.backgroundColor = UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 0.5)
                    toolBar.tintColor = UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 0.5)
                    UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 1.0),
                    NSAttributedString.Key.font: UIFont(name: "Clinton", size: 14)], for: UIControl.State.normal)

        self.toolbar = toolBar
    }

    @objc func doneTapped() {
        self.toolbarDelegate?.didTapDone()
    }

    @objc func cancelTapped() {
        self.toolbarDelegate?.didTapCancel()
    }
}

extension String {
    // formatting text for currency textField
    func currencyFormatting() -> String {
        if let value = Double(self) {
            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
            formatter.maximumFractionDigits = 0
            if let str = formatter.string(for: value) {
                return str
            }
        }
        return ""
    }
}
...