我试图用闭包实现自定义函数。但它不支持#selector
。#选择器与闭包不兼容?
下面是一个例子:
class Core: NSObject {
static let shared:Core = Core.init()
func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion:() -> Void) {
button.layer.cornerRadius = button.bounds.width/2
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor = color
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.addTarget(viewController, action: #selector(completion()), for: .touchUpInside)
}
}
Xcode的给了我一个编译时间问题:
论证 '#selector' 不是指一个 '@objc' 方法,属性,或初始化程序
使用一个属性来存储这样的完成处理程序是***真***脆弱。它不是线程安全的并且容易出现错误 – Alexander
是的,这显然是对@Mannopson问题的简单快速回答。针对当前线程的某些手动检查在多线程情况下会很有用。或者留在主线上,你会没事的。但对于初学者来说,这将使曼诺普森朝着正确的方向前进。 –
我不同意,这当然不是正确的方向。这是一个危险的方法,可能无法完全理解陷阱的人。如果你真的想要将Crowbar封闭到ObjC API中,那么我能想到的唯一方法是实例化一个新类,并将封闭体注册为具有唯一选择器的方法。 – Alexander