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

时间:2021-06-14 20:22:30

标签: swift swift5

我正在尝试为我的按钮/动作制作一个生成器。 我怎么能这样做? >

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

1 个答案:

答案 0 :(得分:2)

你可以试试这个 -

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