Swift5 如何将函数传递给向量/函数

Swift5 how to pass function to a vector/ to a function

我正在尝试为我的 buttons/actions 制作一个发电机。 我怎么能这样做? >

var buttonPairs = [
            [“Reset”,handleReset] // handleHeightReset - function in current self
]

for data in buttonPairs{
    mButtonPtrs[data[0] as! String] = UIButton()
    mButtonPtrs[data[0]!.addTarget(self, action: #selector(data[1]) , for: UIControl.Event.touchUpInside)
}

我不断收到错误消息: swift Argument of ‘#selector’ does not refer to an ‘@objc’ method, property, or initializer

你可以试试这个-

import Foundation
import UIKit

struct ButtonConfig {
    let title: String
    let action: Selector
}

class ViewController: UIViewController {
    @objc func handleReset() {}
    
    var buttonConfigs: [ButtonConfig] = [
        .init(title: "Reset", action: #selector(handleReset))
    ]
    var buttonsCache: [String: UIButton] = [:]
    
    func prepareButtonsCache() {
        for config in buttonConfigs {
            let button = UIButton()
            button.addTarget(self, action: config.action, for: .touchUpInside)
            buttonsCache[config.title] = button
        }
    }
}