当用户按下“添加”按钮时,如何向我的UITableView添加下拉选择?

时间:2019-05-16 18:32:34

标签: swift 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最初不包含任何值,而不是myTableView显示“一个”,“两个”和“三个”,但是当用户从上述下拉菜单中同时选择品牌和型号时,他们按下“添加”按钮,选择将添加到表格视图中。谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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