TextField возвращает ноль, если никогда не выбран повторно - PullRequest
0 голосов
/ 25 апреля 2020

В моем EditV C я выполнил переход из выбранной CellForRow в indexPath для редактирования V C.

In Edit V C. Я хочу ожидать результатов возврата данных, если они не изменяются. Однако проблема в том, что если я не выберу / повторно выберу строку в pickerView снова, она автоматически вернет ноль.

Я хочу получить результаты, если пользователь не изменил только данные / данные c, остальные данные останутся прежними.

Это результаты оператора печати. ​​

// Эти результаты выполняются правильно для того, что я хочу, ЕСЛИ Я ПЕРЕСМОТРЕЛА ВЫБОР ИЗОБРАЖЕНИЯ В ТЕКСТЕЛЕ, НО ИЗМЕНЯЕТ МОЮ КАТЕГОРИЮ БАЗЫ ДАННЫХ.

currentTransaction.categoryID: Необязательно (9)

selectedCategory.categoryID: 9

currentTransaction.categoryTypeID: Необязательно (1)

selectedCategory. categoryTypeID: 1

currentTransaction.categorytype.name = Необязательно ("РАСХОД 9")

selectedCategory.name = РАСХОД 9

// Если я никогда не выберу окно выбора в текстовом поле

currentTransaction.categoryID: необязательно (0) / * Предположим, что оно равно 9 * /

selectedCategory.categoryID: 0 / * Предположим, что это 9 * /

currentTransaction.categoryTypeID: Необязательно (0) / * Предположим, что это 1 * /

selectedCategory.categoryTypeID: 0 / * Предположим, что это 1 * /

currentTransaction.catego ryType.name = Необязательный ("") / * Предположим, что это EXPENSE 9 * /

selectedCategory.name = / * Предположим, что это EXPENSE 9 * /


class EditTransactionTableViewController: UITableViewController {
    let realm = try! Realm()
    var selectedTransaction : Transaction? //selectedTransaction From TransactionVC's CellForRow

    var categories : Results<Category>!
    var currentCategories : Results<Category>!
    var selectedCategory = Category()


    @IBOutlet weak var amountTF: UITextField!

    //PickerView for keyboard
    lazy var pickerView : UIPickerView = UIPickerView()
    //Segment Control
    @IBOutlet weak var categorySCoutlet: UISegmentedControl!
    @IBOutlet weak var categoryTF: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        amountTF.text = selectedTransaction?.amount
        categoryTF.text = selectedTransaction?.categoryType?.name
        categorySCoutlet.selectedSegmentIndex = selectedTransaction?.categoryType?.categoryTypeID as! Int



        loadData()
        setupPicker()
    }


    @IBAction func categoryTypeSC(_ sender: UISegmentedControl) {
        guard let type = CategoryType(id: sender.selectedSegmentIndex) else {
            fatalError("error")
        }
        currentCategories = categories.filter("categoryTypeID == %@", type.rawValue)
        categoryTF.text = currentCategories.first?.name
        pickerView.reloadAllComponents()
//        pickerView.selectRow(0, inComponent: 0, animated: true)

    }


    //MARK:- Edit Transaction Btn

    @IBAction func editTransactionButtonTapped(_ sender: UIButton) {

        if let currentTransaction = selectedTransaction {
            try! realm.write {
                currentTransaction.amount = amountTF.text!


                //Success modification if got RESELECT row of category BUT will return "" if never reselect and cause categories list become chosen categoryID, name , and type
                currentTransaction.categoryType?.categoryID = selectedCategory.categoryID
                currentTransaction.categoryType?.categoryTypeID = selectedCategory.categoryTypeID
                currentTransaction.categoryType!.name = selectedCategory.name



                print("currenttransaction.categoryID : \(currentTransaction.categoryType?.categoryID)")
                print("selectedCategory.categoryID : \(selectedCategory.categoryID)")

                print("currenttransaction.categoryTypeID : \(currentTransaction.categoryType?.categoryTypeID)")
                print("selectedCategory.categoryTypeID : \(selectedCategory.categoryTypeID)")

                print("currenttranasction.categorytype.name = \(currentTransaction.categoryType?.name)")
                print("selectedcategory.name = \(selectedCategory.name)")

            }

        }



        DataManager.shared.transVC.tableView.reloadData()
        dismiss(animated: true, completion: nil)
    }




    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if touches.first?.view == view {
            categoryTF.resignFirstResponder()
        }
    }
    // MARK: - Data Manipulation
    func loadData() {
        categories = realm.objects(Category.self)
    }
}

//MARK:- UIPICKERVIEW DELEGATE

extension EditTransactionTableViewController : UIPickerViewDelegate, UIPickerViewDataSource {

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return currentCategories.count
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return currentCategories[row].name
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        categoryTF.text = currentCategories[row].name
        selectedCategory = currentCategories[row]

    }

    //MARK:- Picker Helper
    func setupPicker() {
//        currentCategories = categories.filter("categoryTypeID == %@", CategoryType.income.rawValue)
        currentCategories = categories.filter("categoryTypeID == %@", selectedTransaction?.categoryType?.categoryTypeID)

        categoryTF.inputView = pickerView

        pickerView.delegate = self
        pickerView.dataSource = self

        categorySCoutlet.setTitle("Income", forSegmentAt: 0)
        categorySCoutlet.setTitle("Expense", forSegmentAt: 1)
        categorySCoutlet.addTarget(self, action: #selector(categoryTypeSC(_:)), for: .valueChanged)

    }
}


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...