我可以在Swift 4中将参数(不是发送方)附加到uiButton.addTarget上吗

时间:2018-09-24 09:34:21

标签: swift uibutton

我是iOS开发的新手。请检查以下代码。

let dropDown = DropDown()

override func viewDidLoad() {
    super.viewDidLoad()

    dropDown.anchorView = dropDownTest // UIView or UIBarButtonItem
    dropDown.dataSource = ["Car", "Motorcycle", "Truck"]
    dropDown.bottomOffset = CGPoint(x: 0, y:(dropDown.anchorView?.plainView.bounds.height)!)
    dropDownTest.addTarget(self, action: #selector(self.buttonClicked(sender:)), for: .touchUpInside)
}

@objc private func buttonClicked(sender: UIButton) {
    dropDown.show()
}

这很容易,因为可以从dropDown方法中调用变量buttonClicked。但是,就我而言,我必须在与表格单元相关的方法cellForRowAt中进行此操作。

        let cell = tableView.dequeueReusableCell(withIdentifier: "VarientCell", for: indexPath)

        let varientButtonTag = 1

        let varientButton = cell.viewWithTag(varientButtonTag) as! UIButton
        let varientDropDown = DropDown()
        varientDropDown.anchorView = varientButton
        varientDropDown.dataSource = datasource
        varientDropDown.bottomOffset = CGPoint(x: 0, y: varientButton.bounds.height)

        varientButton.addTarget(self, action: #selector(self.varientButtonClicked(sender:)), for: .touchUpInside)
        return cell

和单击按钮的方法

    @objc private func varientButtonClicked(sender: UIButton) {
       //dropDown.show() 
       // my problem is here.., i need to pass the dropDown somehow to show that. 
    }

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。我指出了两种可能的方式。 1.您可以继承UIButton并为其添加参数。

class MyButton: UIButton{

       var myParam1: String?
       var myParam2: String?

    }
  1. 创建自定义表格视图单元并处理内部的按钮调用

    导入UIKit

    class MyCell: UITableViewCell{
        @IBOutlet weak var myButton: UIButton!
        @IBOutlet weak var anotherButton: UIButton!
        func setup(model: YourDataModel){
    
            myButton.addTarget(self, action:#selector(self.didSelect(_ :), for: .touchUpInside)
            anotherButton.addTarget(self, action: #selector(self.didSelect(_ :)), for: .touchUpInside)
        }
    
        @objc func didSelect(_ sender: UIButton){
            switch sender {
            case myButton:
                print("my button clicked")
            case anotherButton:
                print("anotherButton clicked")
            default:
                break
            }
        }
    }