如何根据所选的 PickerView 值更新 textField?

How do I update the textField based on the PickerView values that are selected?

所以我附加了一个 UIAlert 和一个 textField。当我在 textField 中单击时,会出现一个 pickerView,然后我会到达 select 星期几。但是,当我在 pickerView 的任何一天 select 时,textField 仅显示 pickerView 中的第一个值,并且当我 select 不同的值时不会更新。正确的 selected 值仍然会被保存并且 tableView 会相应地更新,但是 textField 中的文本不会改变。是因为它在警报中吗?

如有任何帮助,我们将不胜感激。

import UIKit
import RealmSwift

class ViewController: UITableViewController, UITextFieldDelegate {

    let realm = try! Realm()

    var days : Results<Days>?
    var workouts : Results<Workouts>?

    var daysOfWeek : [String] = ["Monday", "Tuesday", "Wednsday", "Thursday", "Friday", "Saturday", "Sunday"]

    var indexCheck : Int = 0

    let picker = UIPickerView()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        picker.delegate = self
        picker.dataSource = self

        navigationItem.title = "Workouts"
        navigationController?.navigationBar.prefersLargeTitles = true

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        let addBarButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addWorkout))
        self.navigationItem.rightBarButtonItem = addBarButton


        loadDays()
    }

    @objc func addWorkout() {
        var textField1 = UITextField()
        var textField2 = UITextField()

        var containsDay = false
        var counter = 0
        textField1.delegate = self
        textField2.delegate = self

        let alert = UIAlertController(title: "New Workout", message: "Please name your workout...", preferredStyle: .alert)

        let addAction = UIAlertAction(title: "Add Workout", style: .default) { (UIAlertAction) in
            //Add day and workout to database
            //if day exists, append workout to the existing day.
            //if day doesn't exist, create a day and append workout to newly created day object.

            //First, we have to create an initial days object...
            //Need to check if ANY of the weekdays == picked day, only execute then.
            if self.days?.isEmpty == false {
                for i in 0...(self.days!.count - 1) {

                    if self.days?[i].weekday == self.daysOfWeek[self.picker.selectedRow(inComponent: 0)] {
                        containsDay = true
                        counter = i
                        break
                    }
                }

                if containsDay == true {
                    let newWorkout = Workouts()
                    newWorkout.title = textField2.text!

                    try! self.realm.write {
                        self.days?[counter].workout.append(newWorkout)
                        self.loadDays()
                    }
                } else {
                    let dow = Days()
                    let newWorkout = Workouts()
                    dow.weekday = self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
                    newWorkout.title = textField2.text!
                    dow.workout.append(newWorkout)
                    self.save(newDay: dow)
                }
            } else {
                let dow = Days()
                let newWorkout = Workouts()
                dow.weekday = self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
                newWorkout.title = textField2.text!
                dow.workout.append(newWorkout)

                self.save(newDay: dow)
            }
        }

        alert.addTextField { (alertTextField1) in
            alertTextField1.placeholder = "Day of Week"
            alertTextField1.text = self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
            textField1 = alertTextField1
            alertTextField1.inputView = self.picker

        }

        alert.addTextField { (alertTextField2) in
            alertTextField2.placeholder = "Muscle Group"
            textField2 = alertTextField2
            alertTextField2.inputView = nil
        }


        alert.addAction(addAction)
        present(alert, animated: true, completion: nil)
    }


    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel()
        label.text = days?[section].weekday ?? "Section Header"
        label.backgroundColor = UIColor.lightGray
        return label
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return days?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return days?[section].workout.count ?? 0
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let workout = days?[indexPath.section].workout[indexPath.row].title ?? "Workout"

        cell.textLabel?.text = "\(workout)  Section:\(indexPath.section) Row:\(indexPath.row)"

        return cell
    }


    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {
            try! realm.write {
                realm.delete((days?[indexPath.section].workout[indexPath.row])!)

                tableView.beginUpdates()

                tableView.deleteRows(at: [indexPath], with: .automatic)

                if days?[indexPath.section].workout.isEmpty == true {
                    realm.delete((days?[indexPath.section])!)
                    let indexSet = IndexSet(arrayLiteral: indexPath.section)
                    tableView.deleteSections(indexSet, with: .automatic)
                }

                tableView.endUpdates()
            }
        }
    }



    func loadDays() {
        days = realm.objects(Days.self)
        tableView.reloadData()
    }

    func save(newDay : Days) {
        do {
            try realm.write {
                realm.add(newDay)
            }
        } catch {
            print("Error saving day \(error)")
        }
        self.loadDays()
    }

}



extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource {

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 7
    }

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

}

声明textfield对象为全局对象,使用PickerView的didSelectRow方法根据选择改变textfield的值。

例如:-

let picker = UIPickerView()
var textField1 = UITextField()

接下来,使用以下方法获取所选值:-

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField1.text = daysOfWeek[row]
}

将您的两个文本字段对象声明为全局对象

var textField1 = UITextField()
var textField2 = UITextField()

添加在您的代码中更新的 pickerview 委托方法:

extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource {

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 7
    }

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

   func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        textField1.text = daysOfWeek[row]
    }

}