首页 > 解决方案 > 我可以在 Swift 4 中将参数(不是发件人)附加到 uiButton.addTarget

问题描述

我是 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. 
    }

标签: swiftuibutton

解决方案


有很多方法可以做到这一点。我指的是两种可能的方法。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
            }
        }
    }
    

推荐阅读