如何在Swift中以编程方式制作UIButton时传递函数



我想传递一个函数作为参数,并在UITableView扩展中使用它。在名为"setEmptyView"的函数中,我以编程方式制作了UIButton,并添加了一些目标操作。以下是我迄今为止所做的工作。

extension UITableView {
func setEmptyView(message: String, actionButtonClosure: @escaping () -> Void) {
let emptyView = UIView()
let messageLabel = UILabel()
let button = UIButton()
// adding subview and making constraints codes....
button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
}
@objc func buttonAction (_ sender: UIButton!) {
actionButtonClosure()    <---- error
}
}
class ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if count == 0 {
let message = "Here is placeholder for this table"
tableView.setEmptyView(message: message, buttonTitle: "see more") { [self] in
goToMenu()
}
}
return count
}
func goToMenu() {
// move to next VC
}

很遗憾,参数中的"actionButtonClosure"函数无法访问,因为它是两个不同的函数。我也尝试过将.addAction((添加到按钮中,但它只有在iOS14之后才可用。你建议在这里做什么?如何传递函数参数并将其用作按钮操作?

我的解决方案一点也不花哨,但至少它可以工作。

在扩展插件内创建一个类型为(() -> Void)?static var。我会给你看:

extension UITableView {
static var buttonClosure: ( () -> Void)?
func setEmptyView(message: String, actionButtonClosure: @escaping () -> Void) {
let emptyView = UIView()
let messageLabel = UILabel()
let button = UIButton()
// Assign the action to the var
Self.buttonClosure = actionButtonClosure

// adding subview and making constraints codes....
button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
}
@objc func buttonAction (_ sender: UIButton!) {
// Safe unwrapped to avoid crashes
if let closure = Self.buttonClosure {

// Execute the function
closure()
// Uncomment the next line if you want avoid repeat the action more than one
// Self.buttonClosure = nil
}
}
}
...

这对你有用。问候和愉快的编码

最新更新