Swift Dictionary UIPickerView(键)和UITableView(值)

时间:2018-01-10 19:52:26

标签: ios swift uitableview dictionary uipickerview

Img: Now the app: data does not change

Img: Now the app: data does not change

我目前正在使用Swift开发一个应用程序,我使用UIPickerView和TableView(这适用于单一视图)。我想更改pickerView(myPickerView)中的键,将TableView(myTableView)中的值更改为正确的数据(自动)。

import UIKit

struct Cars {

    var carName: String!
    var carModel: [String]!

}

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDataSource, UITableViewDelegate {

    // Dictionary
   var myDictionary = [
    "BMW": ["M3", "M4", "M5"],
    "Porsche": ["Panamera", "911", "Cayenne"],
    "Audi": ["RS4", "RS6", "RS5"],
    "Mercedes": ["Class S", "SL", "AMG GTR"]
    ]

    // Array
    var allObjects = [Cars]()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        // Func - Constraint PickerView/TableView/Button
        setupUI()

        // PickerView Delegate/DataSource
        myPickerView.dataSource = self
        myPickerView.delegate = self

        // TableView Delegate/DataSource
        myTableView.delegate = self
        myTableView.dataSource = self

        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")

        // Loop key and value - myDictionary
        for (key, value) in myDictionary {

            allObjects.append(Cars(carName: key, carModel: value))
        }
    }

    // My TableView
    let myTableView: UITableView = {
       let tv = UITableView()
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()

    // My PickerView
    let myPickerView: UIPickerView = {
        let bp = UIPickerView()
        bp.translatesAutoresizingMaskIntoConstraints = false
        return bp
    }()

    // Button Open myPickerView and setup nameCar
    var myChoiceCarNameButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Choice Car", for: .normal)
        button.tintColor = .black
        button.addTarget(self, action: #selector(handleChoiceCarName), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    // Target selector button "myChoiceCarNameButton"
    @objc func handleChoiceCarName() {
        print("Tapped choice car name ")

        view.layoutIfNeeded()
        UIView.animate(withDuration: 0.25, animations: {

            self.view.layoutIfNeeded()

        }) { (completed) in

            UIView.animate(withDuration: 0.25, animations: {

                self.myPickerView.alpha = 1
                self.view.layoutIfNeeded()
            })
        }
    }

    // Constraint button/pickerView/TableView
    private func setupUI() {

        view.addSubview(myChoiceCarNameButton)
        myChoiceCarNameButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
        myChoiceCarNameButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        myChoiceCarNameButton.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        myChoiceCarNameButton.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true


        view.addSubview(myPickerView)
        myPickerView.alpha = 0
        myPickerView.topAnchor.constraint(equalTo: myChoiceCarNameButton.bottomAnchor).isActive = true
        myPickerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        myPickerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true


        view.addSubview(myTableView)
        myTableView.topAnchor.constraint(equalTo: myPickerView.bottomAnchor, constant: 10).isActive = true
        myTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        myTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        myTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10).isActive = true
    }

    // MARK: - PickerViewDelegate/DataSource Methods

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

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

        if component == 0 {
            return allObjects.count
        } else {
            let selectedBody = pickerView.selectedRow(inComponent: 0)
            return allObjects[selectedBody].carName.count
        }
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if component == 0 {
            return allObjects[row].carName
        } else {
            let selectedCar = pickerView.selectedRow(inComponent: 0)
            return allObjects[selectedCar].carName
        }
    }

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

        // Set the button title
        myChoiceCarNameButton.setTitle(allObjects[row].carName, for: .normal)

        view.layoutIfNeeded()
        UIView.animate(withDuration: 0.25, animations: {

            self.myPickerView.alpha = 0
            self.view.layoutIfNeeded()

        }) { (completed) in

            UIView.animate(withDuration: 0.25, animations: {

                self.view.layoutIfNeeded()
                self.myTableView.reloadData()
            })

        }

    } // End did select



    // MARK: - TableViewDelegate/DataSource Methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return allObjects[section].carModel.count
    }

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

        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        cell.textLabel?.text = allObjects[indexPath.section].carModel[indexPath.row]
        return cell
    }

} // End class

也许有人发现了类似的情况并知道该怎么做? 也许某人更容易解决如何实现这种效果?

1 个答案:

答案 0 :(得分:0)

问题在于:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return allObjects[section].carModel.count
}

当用户在func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)功能中做出选择时,您必须将选定的汽车保存在变量中。然后在numberOfRowsInSection函数中,您必须使用此变量:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return allObjects[selectedCarIndex].carModel.count
}

另外,您没有指定func numberOfSections(in tableView: UITableView) -> Int委托方法,因此我假设默认值始终为1,因此UITableView中只有1个部分。因此,在func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int委托方法中,该部分始终为1,因此这就是您在UITableView中看不到任何更改的原因。