gpt4 book ai didi

ios - 带有按钮和选择器的协议(protocol)扩展

转载 作者:行者123 更新时间:2023-11-28 23:38:34 25 4
gpt4 key购买 nike

我有一些协议(protocol):

@objc protocol SomeProtocol { } 

我为 UIViewController 实例扩展。在此扩展中,我想创建并添加一个按钮,其选择器也在协议(protocol)中定义:

extension SomeProtocol where Self: UIViewController {

func addSomeButton() {
let someButton = UIButton()
someButton.addTarget(self, #selector(someButtonPressed), for: .touchUpInside)
view.addSubview(someButton)
}

@objc func someButtonPressed() {
}

}

但是,我在 someButtonPressed 的定义处收到错误消息:@objc 只能与类成员、@objc 协议(protocol)和类的具体扩展一起使用

有什么方法可以使用协议(protocol)来实现吗?

提前感谢您的任何建议!

最佳答案

解决方法是向 UIButton 添加一个闭合 socket ,而不是此处所示的目标操作 https://stackoverflow.com/a/41438789/5058116并为方便起见复制在下面。

typealias Closure = () -> ()

///
class ClosureSleeve {
let closure: Closure
init(_ closure: @escaping Closure) {
self.closure = closure
}
@objc func invoke () {
closure()
}
}

extension UIControl {
func addAction(for controlEvents: UIControl.Event = .touchUpInside, _ closure: @escaping Closure) {
let sleeve = ClosureSleeve(closure)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}

然后简单地替换:

someButton.addTarget(self, #selector(someButtonPressed), for: .touchUpInside)

与:

someButton.addAction { [weak self] in
self?.someButtonPressed()
}

嘿嘿。

关于ios - 带有按钮和选择器的协议(protocol)扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54155094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com