首页 > 解决方案 > 当用户按下“添加”按钮时,如何向我的 UITableView 添加下拉选择?

问题描述

目前,myTableView 包含“一”、“二”和“三”。但是,我希望保持空白,直到用户从上面的下拉选项中同时选择品牌和型号,并且一旦按下“添加”按钮,我希望将数据传递到 myTableView。

导入 UIKit

var myTableView: UITableView = UITableView()


struct Section {
    var make: String
    var model: [String]
}

var Cars = [
    Section(make: "Any", model: ["Any"]),
    Section(make: "BMW", model: ["A","B","C"]),
    Section(make: "Ford", model: ["D","E","F"]),
    Section(make: "Audi", model: ["G","H","I"]),
    Section(make: "Bentley", model: ["J","K","L"])
]


var carMake = Cars.map({$0.make})

class ViewController: UIViewController,DropDownBtnProtocol, UITableViewDataSource, UITableViewDelegate {
    func optionChanged(_ button: DropDownBtn, string: String) {
        if button == makeButton {
            if let selectedMake = Cars.first(where: { $0.make == string }) {
                modelButton.dropView.dropDownOptions = selectedMake.model
                self.view.bringSubviewToFront(modelButton.dropView)

            }
        } else if button == modelButton {

        }
    }


    ////Set up buttons
    var makeButton = DropDownBtn()
    var modelButton = DropDownBtn()
    var addButton = UIButton()



    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Innocent Sheep"


        view.backgroundColor = .white
        makeButton = DropDownBtn.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        makeButton.delegate = self
        makeButton.setTitle("Select Make", for: .normal)
        makeButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        makeButton.translatesAutoresizingMaskIntoConstraints = false



        self.view.addSubview(makeButton)

        makeButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        makeButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -300).isActive = true

        makeButton.widthAnchor.constraint(equalToConstant: 450).isActive = true
        makeButton.heightAnchor.constraint(equalToConstant: 50).isActive = true

        makeButton.dropView.dropDownOptions = carMake

        modelButton = DropDownBtn.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        modelButton.delegate = self
        modelButton.setTitle("Select Model", for: .normal)
        modelButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        modelButton.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(modelButton)

        modelButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        modelButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -240).isActive = true

        modelButton.widthAnchor.constraint(equalToConstant: 450).isActive = true
        modelButton.heightAnchor.constraint(equalToConstant: 50).isActive = true



        let addButton = UIButton.init(type: .system)
        addButton.frame = CGRect(x: 50, y: 300, width: 60, height: 40)
        addButton.layer.cornerRadius = 5
        addButton.setTitle("Add", for: .normal)
        addButton.layer.borderWidth = 2.5
        addButton.layer.borderColor = UIColor.black.cgColor
        addButton.addTarget(self, action: #selector(buttonClicked(_ :)), for: .touchUpInside)
        self.view.addSubview(addButton)
    }


    @objc func buttonClicked(_: UIButton) {
        print("tapped")
    }

        var itemsToLoad: [String] = ["One", "Two", "Three"]

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)

            let screenSize: CGRect = UIScreen.main.bounds

            let screenWidth = screenSize.width
            let screenHeight = (screenSize.height / 2)

            myTableView.frame = CGRect(x: 0, y: 500, width: screenWidth, height: screenHeight)
            myTableView.dataSource = self
            myTableView.delegate = self

            myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
            self.view.addSubview(myTableView)
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return itemsToLoad.count
        }

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

            cell.textLabel?.text = self.itemsToLoad[indexPath.row]

            return cell
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])")
        }
}


protocol DropDownBtnProtocol {
    func optionChanged(_ button: DropDownBtn, string: String)
}
class DropDownBtn: UIButton, DropDownViewProtocol {
    func dropDownPressed(string: String) {
        self.setTitle(string, for: .normal)
        self.dismissMakeDropDown()
        delegate.optionChanged(self, string: string)
    }
    var delegate: DropDownBtnProtocol!
    var dropView = DropDownView()
    var height = NSLayoutConstraint()
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.backgroundColor = UIColor(red: 52/255, green: 49/255, blue: 78/255, alpha: 1)
        dropView = DropDownView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        dropView.delegate = self
        dropView.translatesAutoresizingMaskIntoConstraints = false
    }
    override func didMoveToSuperview() {
        self.superview?.addSubview(dropView)
        self.superview?.bringSubviewToFront(dropView)
        dropView.topAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        dropView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        dropView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        height = dropView.heightAnchor.constraint(equalToConstant: 0)
    }
    var makeisOpen = false
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if makeisOpen == false {
            makeisOpen = true
            NSLayoutConstraint.deactivate([self.height])
            if self.dropView.tableView.contentSize.height > 150 {
                self.height.constant = 150
                self.superview?.bringSubviewToFront(dropView)
            } else {
                self.height.constant = self.dropView.tableView.contentSize.height
            }
            NSLayoutConstraint.activate([self.height])
            UIView.animate(withDuration: 0.5, delay: 0,
                           usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options:
                .curveEaseInOut, animations: {self.dropView.layoutIfNeeded()
                    self.dropView.center.y += self.dropView.frame.height / 2
            }, completion: nil)
        } else {
            makeisOpen = false
            NSLayoutConstraint.deactivate([self.height])
            self.height.constant = 0
            NSLayoutConstraint.activate([self.height])
            UIView.animate(withDuration: 0.5, delay: 0,
                           usingSpringWithDamping: 0.5,initialSpringVelocity: 0.5, options:
                .curveEaseInOut, animations: {
                    self.dropView.center.y -= self.dropView.frame.height / 2
                    self.dropView.layoutIfNeeded()

            }, completion: nil)
        }
    }
    func dismissMakeDropDown() {
        makeisOpen = false
        NSLayoutConstraint.deactivate([self.height])
        self.height.constant = 0
        NSLayoutConstraint.activate([self.height])
        UIView.animate(withDuration: 0.5, delay: 0,
                       usingSpringWithDamping: 0.5,initialSpringVelocity: 0.5, options:
            .curveEaseInOut, animations: {
                self.dropView.center.y -= self.dropView.frame.height / 2
                self.dropView.layoutIfNeeded()

        }, completion: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
protocol DropDownViewProtocol {
    func dropDownPressed(string: String)
}
class DropDownView: UIView, UITableViewDelegate,UITableViewDataSource {

    var dropDownOptions = [String]() {
        didSet {
            tableView.reloadData()
        }
    }
    var tableView = UITableView()
    var delegate : DropDownViewProtocol!

    override init(frame: CGRect) {
        super.init(frame: frame)
        tableView.backgroundColor = UIColor.white
        self.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(tableView)
        tableView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dropDownOptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath:
        IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel!.text = dropDownOptions[indexPath.row]
        cell.backgroundColor = UIColor.init(red: 255/255, green: 160/255, blue: 122/255, alpha: 0.8)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.delegate.dropDownPressed(string: dropDownOptions[indexPath.row])
    }

    class DropDownView: UIView, UITableViewDelegate,UITableViewDataSource {

        var optionstableView = UITableView()


        override init(frame: CGRect) {
            super.init(frame: frame)
            optionstableView.backgroundColor = UIColor.red
            self.backgroundColor = UIColor.red
            optionstableView.delegate = self
            optionstableView.dataSource = self
            optionstableView.translatesAutoresizingMaskIntoConstraints = false

            self.addSubview(optionstableView)

            optionstableView.leftAnchor.constraint(equalTo: optionstableView.leftAnchor, constant: 32).isActive = true
            optionstableView.topAnchor.constraint(equalTo: optionstableView.topAnchor, constant: 120).isActive = true
            optionstableView.rightAnchor.constraint(equalTo: optionstableView.rightAnchor, constant: -32).isActive = true
            optionstableView.bottomAnchor.constraint(equalTo: optionstableView.bottomAnchor, constant: -32).isActive = true

        }
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 25
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath:
            IndexPath) -> UITableViewCell {
            let cell = UITableViewCell()
            cell.textLabel!.text = "dropDownOptions[indexPath.row]"
            cell.backgroundColor = UIColor.init(red: 255/255, green: 160/255, blue: 122/255, alpha: 0.8)
            return cell
        }
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        }



        }

        }

而不是 myTableView 显示“一”、“二”和“三”,我希望它最初不包含任何值,但是当用户从上面的下拉菜单中选择品牌和型号并按下“添加”按钮时,选择被添加到表视图中。谢谢你。

标签: swiftuitableview

解决方案


首先,我不知道您是否只是复制和粘贴内容,或者您​​的实际文件看起来像这样。如果您的文件实际上看起来像这样,那么您需要学习代码组织的最佳实践并进行一些清理。

其次,不确定是否要添加单元格、部分或其他内容。在快速扫描您的代码后,我看到您以编程方式创建了一些很好的约束,但我建议使用自定义视图或自定义 UITableViewCell 来包含自定义视图并将其他与视图相关的约束放在那里。

所以让我们回到这个话题,如果你只是想让用户在下拉选择中选择两个东西然后插入 UITableViewCell 那么你就可以做到。只需要添加一些逻辑来处理它,并记住在插入和删除表格视图单元格时更新显示数据。但我建议在添加更多逻辑之前先清理一下代码。


推荐阅读