gpt4 book ai didi

ios - 从协议(protocol)扩展调用选择器

转载 作者:IT王子 更新时间:2023-10-29 05:48:09 25 4
gpt4 key购买 nike

我正在构建简单的主题引擎,并且想要一个将 UISwipeGestureRecognizer 添加到 UIViewController 的扩展

这是我的代码:

protocol Themeable {
func themeDidUpdate(currentTheme: Theme) -> Void
}

extension Themeable where Self: UIViewController {
func switchCurrentTheme() {
Theme.switchTheme()
themeDidUpdate(Theme.currentTheme)
}

func addSwitchThemeGestureRecognizer() {
let gestureRecognizer = UISwipeGestureRecognizer(target: self, action:#selector(Self.switchCurrentTheme))
gestureRecognizer.direction = .Down
gestureRecognizer.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(gestureRecognizer)
}
}

当然,编译器找不到 #selector(Self.switchCurrentTheme),因为它没有通过 @objc 指令公开。是否可以将此行为添加到我的扩展中?

更新: Theme 是一个 Swift 枚举,所以我不能在 Themeable 前面添加 @objc > 协议(protocol)

最佳答案

我能想到的最干净、可行的解决方案是使用相关方法在 UIViewController 上定义一个私有(private)扩展。通过将范围限制为 private,可以将对此方法的访问隔离到定义协议(protocol)的源文件中。如下所示:

protocol Themeable {
func themeDidUpdate(currentTheme: Theme) -> Void
}

fileprivate extension UIViewController {
@objc func switchCurrentTheme() {
guard let themeableSelf = self as? Themeable else {
return
}

Theme.switchTheme()
themeableSelf.themeDidUpdate(Theme.currentTheme)
}
}

extension Themeable where Self: UIViewController {
func addSwitchThemeGestureRecognizer() {
let gestureRecognizer = UISwipeGestureRecognizer(target: self, action:#selector(switchCurrentTheme))
gestureRecognizer.direction = .Down
gestureRecognizer.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(gestureRecognizer)
}
}

关于ios - 从协议(protocol)扩展调用选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629301/

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