Попытка отфильтровать значения в одном раскрывающемся меню в зависимости от значения, выбранного в другом раскрывающемся меню в Swift. - PullRequest
1 голос
/ 12 мая 2019

У меня есть два выпадающих меню, одно из которых содержит марки автомобилей, а другое - модели автомобилей. Когда я выбираю марку автомобиля, можно ли отфильтровать значения в выпадающих моделях, чтобы показать только те, которые соответствуют этой конкретной марке?

В настоящее время, когда я выбираю марку автомобиля из меню, значение заголовка изменится на любое выбранное. Я пытался использовать это значение в качестве параметра для фильтрации параметров модели, но мне не повезло. Надеюсь, я сделал это достаточно ясно:)

import UIKit

class ViewController: UIViewController {

 ////Set up buttons

var makeButton = makeDropDownBtn()
var modelButton = modelDropDownBtn()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically 
   from a nib.


    makeButton = makeDropDownBtn.init(frame: CGRect(x: 0, y: 0,   
 width: 0, height: 0))
    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.makeDropView.dropDownOptions = carMake

    modelButton = modelDropDownBtn.init(frame: CGRect(x: 0, y: 0, 
width: 0, height: 0))
    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

    modelButton.modelDropView.modelDropDownOptions = carModel
    }

   }
  protocol makeDropDownProtocol {
    func makeDropDownPressed(string: String)

  }

  protocol modelDropDownProtocol {
  func modelDropDownPressed(string: String)
  }



  class modelDropDownBtn: UIButton, modelDropDownProtocol {
  func modelDropDownPressed(string: String) {
    self.setTitle(string, for: .normal)
    self.dismissModelDropDown()
  }


  var modelDropView = modelDropDownView()
  var modelheight = NSLayoutConstraint()

  override init(frame: CGRect) {
    super.init(frame:frame)

    self.backgroundColor = UIColor(red: 52/255, green: 49/255, 
   blue: 78/255, alpha: 1)

    modelDropView = modelDropDownView.init(frame: CGRect(x: 0, y: 
   0, width: 0, height: 0  ))
    modelDropView.modelDelegate = self
    modelDropView.translatesAutoresizingMaskIntoConstraints = 
  false


  }

override func didMoveToSuperview() {

    self.superview?.addSubview(modelDropView)
    self.superview?.bringSubviewToFront(modelDropView)

    modelDropView.topAnchor.constraint(equalTo:  
  self.bottomAnchor).isActive = true
    modelDropView.centerXAnchor.constraint(equalTo:
  self.centerXAnchor).isActive = true
    modelDropView.widthAnchor.constraint(equalTo: 
self.widthAnchor).isActive = true
    modelheight =  
 modelDropView.heightAnchor.constraint(equalToConstant: 0)

}

var isOpen = false

override func touchesBegan(_ touches: Set<UITouch>, with event: 
UIEvent?) {
    if isOpen == false {

        isOpen = true

        NSLayoutConstraint.deactivate([self.modelheight])

        if self.modelDropView.modelTableView.contentSize.height > 
150 {
        self.modelheight.constant = 150
        } else {
            self.modelheight.constant = 
self.modelDropView.modelTableView.contentSize.height
        }

        NSLayoutConstraint.activate([self.modelheight])

        UIView.animate(withDuration: 0.5, delay: 0, 
usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: 
.curveEaseInOut, animations: {
            self.modelDropView.layoutIfNeeded()
            self.modelDropView.center.y += 
self.modelDropView.frame.height / 2
        }, completion: nil)
    } else {

isOpen = false

        NSLayoutConstraint.deactivate([self.modelheight])
        self.modelheight.constant = 0
        NSLayoutConstraint.activate([self.modelheight])

        UIView.animate(withDuration: 0.5, delay: 0, 
  usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, 
options: .curveEaseInOut, animations: {
            self.modelDropView.center.y -= 
self.modelDropView.frame.height / 2
            self.modelDropView.layoutIfNeeded()
        }, completion: nil)
    }
}

func dismissModelDropDown() {

    isOpen = false

    NSLayoutConstraint.deactivate([self.modelheight])
    self.modelheight.constant = 0
    NSLayoutConstraint.activate([self.modelheight])

    UIView.animate(withDuration: 0.5, delay: 0, 
usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options:
.curveEaseInOut, animations: {
        self.modelDropView.center.y -= 
self.modelDropView.frame.height / 2
        self.modelDropView.layoutIfNeeded()
    }, completion: nil)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

class makeDropDownBtn: UIButton, makeDropDownProtocol {

func makeDropDownPressed(string: String) {
    self.setTitle(string, for: .normal)
    self.dismissMakeDropDown()
}


var makeDropView = makeDropDownView()

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)

    makeDropView = makeDropDownView.init(frame: CGRect.init(x: 0, 
y: 0, width: 0, height: 0))
    makeDropView.delegate = self
    makeDropView.translatesAutoresizingMaskIntoConstraints = false


}
override func didMoveToSuperview() {

    self.superview?.addSubview(makeDropView)
    self.superview?.bringSubviewToFront(makeDropView)

    makeDropView.topAnchor.constraint(equalTo: 
self.bottomAnchor).isActive = true
    makeDropView.centerXAnchor.constraint(equalTo: 
self.centerXAnchor).isActive = true
    makeDropView.widthAnchor.constraint(equalTo: 
self.widthAnchor).isActive = true
    height = makeDropView.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.makeDropView.tableView.contentSize.height > 150 {
        self.height.constant = 150
                self.superview?.bringSubviewToFront(makeDropView)

        } else {
            self.height.constant =
 self.makeDropView.tableView.contentSize.height
        }
        NSLayoutConstraint.activate([self.height])

        UIView.animate(withDuration: 0.5, delay: 0, 
usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: 
.curveEaseInOut, animations: {self.makeDropView.layoutIfNeeded()
              self.makeDropView.center.y += 
self.makeDropView.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.makeDropView.center.y -= 
self.makeDropView.frame.height / 2
            self.makeDropView.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.makeDropView.center.y -= 
self.makeDropView.frame.height / 2
        self.makeDropView.layoutIfNeeded()

    }, completion: nil)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}





/////Drop Down View Setup
struct Section {
    var make: String
    var model: [String]
}

var Cars = [
    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})

var carModel = Cars.flatMap({$0.model})


 class makeDropDownView: UIView,  
 UITableViewDelegate,UITableViewDataSource {

var dropDownOptions = [String]()

var tableView = UITableView()

var delegate : makeDropDownProtocol!

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 Cars.map({$0.make}).count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath:
 IndexPath) -> UITableViewCell {
    var 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.makeDropDownPressed(string: 
dropDownOptions[indexPath.row])

}
}

 ///model drop down view setup

class modelDropDownView: UIView, UITableViewDelegate, 
    UITableViewDataSource {

var modelDropDownOptions = [String] ()

var modelTableView = UITableView()

var modelDelegate : modelDropDownProtocol!

override init(frame: CGRect) {
    super.init(frame: frame)

    modelTableView.backgroundColor = UIColor.green
    self.backgroundColor = UIColor.green

    modelTableView.delegate = self
    modelTableView.dataSource = self

    modelTableView.translatesAutoresizingMaskIntoConstraints =   
 false

    self.addSubview(modelTableView)

    modelTableView.leftAnchor.constraint(equalTo: 
self.leftAnchor).isActive = true
    modelTableView.rightAnchor.constraint(equalTo: 
self.rightAnchor).isActive = true
    modelTableView.topAnchor.constraint(equalTo: 
self.topAnchor).isActive = true
    modelTableView.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 Cars.flatMap({$0.model}).count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
    var modelCell = UITableViewCell()

    modelCell.textLabel!.text =
 modelDropDownOptions[indexPath.row]
    modelCell.backgroundColor = UIColor.green

    return modelCell

}

func makeselection(_ tableView: UITableView, didSelectRowAt 
indexPath: IndexPath) {

    self.modelDelegate.modelDropDownPressed(string: 
modelDropDownOptions[indexPath.row])

}
}

Надеюсь, можно отфильтровать результаты модели на основе того, что я выбираю в выпадающем списке. Заранее спасибо.

1 Ответ

0 голосов
/ 12 мая 2019
  • Вам не нужно создавать два подкласса UIButton и два подкласса UIView. Вы можете создать один класс и создать несколько экземпляров.

  • Не устанавливайте dropDownOptions для кнопки модели, пока не будет выбрана марка.

  • Когда выбрана марка, получить модель из выбранной марки и установить в модели dropDownOptions.

Просто скопируйте этот код и запустите. Работает

/////Drop Down View Setup
struct Section {
    var make: String
    var model: [String]
}

var Cars = [
    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 {
    func optionChanged(_ button: DropDownBtn, string: String) {
        if button == makeButton {
            if let selectedMake = Cars.first(where: { $0.make == string }) {
                modelButton.dropView.dropDownOptions = selectedMake.model
            }
        } else if button == modelButton {

        }
    }

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


    override func viewDidLoad() {
        super.viewDidLoad()
        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

    }
}
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])
    }
}

enter image description here

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