我该如何修复这个代码, 不阻止对象
class EIUIBarButtonItem: UIBarButtonItem {
typealias HandleClosure = (UIBarButtonItem) -> Void
fileprivate var handle: HandleClosure?
init(image: UIImage?, style: UIBarButtonItemStyle, handle: HandleClosure? = nil) {
self.handle = handle
super.init()
self.image = image
self.style = style
self.target = self
self.action = #selector(buttonAction(_:))
}
// ...OtherCode...
@objc func buttonAction(_ sender: UIBarButtonItem) {
handle?(sender)
}
}
如果我将此按钮创建为
EIUIBarButtonItem(image: myUIImage, style: .plain, handle: controller.buttonAction)
我阻止了对象 Controller
。我怎样才能做一些这样的事情?我的句柄需要弱变量
weak var handle: HandleClosure?
或者类似的东西(@unowned)
EIUIBarButtonItem(image: myUIImage, style: .plain, handle: @unowned controller.buttonAction)
最佳答案
不要直接传递对 Controller 方法的引用,而是将其包装在闭包中。
... handle: { [weak controller] button in controller?.buttonAction(button) })
关于swift - 类似于闭包的弱var之类的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50402707/