ios - 无法以编程方式检查下拉按钮中的按钮标题

标签 ios swift

我是 Swift 的新手,我的英语不是很好

问题是我根据本教程构建了一个下拉 View

YouTube:https://youtu.be/22zu-OTS-3M 知乎:https://github.com/Archetapp/Drop-Down-Menu

他以编程方式创建了一个没有 Storyboard的奇妙下拉 View

代码在我的 Xcode 上运行得很好

但是当我用按钮去查看标题的时候

我从来没有得到它。

这是我的代码

class ViewController: UIViewController, GMSMapViewDelegate

      override func viewDidLoad() 
      super.viewDidLoad()

      let typeBTN = dropDownBtn()
         self.view.addSubview(typeBTN)
         typeBTN.setTitle("animal", for: .normal)
         typeBTN.dropView.dropDownOptions = ["dog", "cat", "cow", "boy"]


 // ....

protocol dropDownProtocol {
    func dropDownPressed(string: String)
}

class dropDownBtn: UIButton, dropDownProtocol {

    func dropDownPressed(string: String) {
        self.setTitle(string, for: .normal)
        self.dismissDropDown()
    }

    var dropView = dropDownView()
    var height = NSLayoutConstraint()



    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.darkGray

        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 isOpen = false

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

        if isOpen == false {
            isOpen = true
            NSLayoutConstraint.deactivate([self.height])
            if self.dropView.tableView.contentSize.height > 150 {
                self.height.constant = 170
            } 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: .curveEaseOut, animations: {
                self.dropView.layoutIfNeeded()
                self.dropView.center.y += self.dropView.frame.height / 2
            }, completion: nil)

        }else{ dismissDropDown() }
    }

    func dismissDropDown() {
        isOpen = 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: .curveEaseOut, 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")
    }
}

class dropDownView: UIView, UITableViewDelegate, UITableViewDataSource { 

    var dropDownOptions = [String]()
    var tableView = UITableView()
    var delegate: dropDownProtocol!

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

        tableView.backgroundColor = UIColor.darkGray
        tableView.delegate = self
        tableView.dataSource = self
        self.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        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.darkGray
        return cell
    }

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

        self.delegate.dropDownPressed(string: dropDownOptions[indexPath.row])

        print(dropDownOptions[indexPath.row])

我已经尝试了很多检查按钮标题何时更改。像这样

 print(typeBTN.currentTitle!)
 print(typeBTN.titleLabel?.text! )
 print(typeBTN.title(for: .normal))
 //I get nothing when i pressed dropdown menu options?

因为我想做这个

if typeBTN.currentTitle == "dog" {
        //show some date at my mapview
    }

但是当我点击下拉菜单的“狗”时

永远不会成功

有人可以帮帮我吗?

最佳答案

您可以使用委托(delegate)模式将标题更改通知给您的 View Controller 。

添加协议(protocol):

protocol DropDownButtonDelegate: AnyObject {
    func titleDidChange(_ newTitle: String)
}

在您的 DropDownButton 类中添加一个委托(delegate)属性:

weak var delegate: DropDownButtonDelegate?

然后在您的 dropDownPressed 函数中:

func dropDownPressed(string: String) {
    self.setTitle(string, for: .normal)
    self.dismissDropDown()
    delegate?.titleDidChange(string)
}

最后在您的 View Controller 中实现 DropDownButtonDelegate:

class ViewController: UIViewController, GMSMapViewDelegate {

    override func viewDidLoad() {
      super.viewDidLoad()

      let typeBTN = dropDownBtn()
      self.view.addSubview(typeBTN)
      typeBTN.delegate = self 
      typeBTN.setTitle("animal", for: .normal)
      typeBTN.dropView.dropDownOptions = ["dog", "cat", "cow", "boy"]
    }
}

extension ViewController: DropDownButtonDelegate {
    func titleDidChange(_ newTitle: String) {
        print(newTitle)
    }
}

关于ios - 无法以编程方式检查下拉按钮中的按钮标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673381/

相关文章:

ios - 如何从 UICollectionViewFlowLayout 中删除换行符

iphone - UIDatePicker 仅显示年份

ios - UITableView 或 UICollectionView 提供类似 Siri 的简单用户体验

ios - 如何正确编码 URL 字符串

ios - 从项目中删除 Pod - xcode

ios - 如何编辑 Realm 对象并保存编辑?

ios - 如何制作双线边框的UIButton?

swift - 如何在 TextField (SwiftUI) 上添加底线

ios - SceneKit 检测 SCNode 何时不移动

ios - Swift 2 SkScene 更改