gpt4 book ai didi

ios - 协议(protocol)扩展中的 Swift 闭包

转载 作者:可可西里 更新时间:2023-11-01 00:51:16 24 4
gpt4 key购买 nike

当从另一个类(例如网络状态管理器)调用 setInteractionEnabled 方法时,我想装饰 UIViewController 以调整它的界面。应通过覆盖 onInteractionChanged 在具体 Controller 中提供所有更改(如果有)。这是我的代码:

import Foundation

typealias InteractionClosure = ((enabled: Bool) -> Void)

protocol Interaction: class {

var onInteractionChanged: InteractionClosure? { get set }

func setInteractionEnabled(enabled: Bool)

}

extension Interaction where Self: UIViewController {

// Default: Do nothing
// Throws: - Extensions may not contain stored properties
var onInteractionChanged: InteractionClosure? = nil

func setInteractionEnabled(enabled: Bool) {
onInteractionChanged?(enabled: enabled)
}

}

extension UIViewController : Interaction {}

如何为 onInteractionChanged 添加默认实现?

最佳答案

我通常不会回答自己的问题,但这是我的解决方案:

typealias InteractionClosure = (enabled: Bool) -> Void

protocol Interaction: class {

func addOnInteractionChanged(closure: InteractionClosure)
func setInteractionEnabled(enabled: Bool)

}

extension Interaction where Self: UIViewController {

func addOnInteractionChanged(closure: InteractionClosure) {
onInteractionChanged = closure
}

func setInteractionEnabled(enabled: Bool) {
onInteractionChanged?(enabled: enabled)
}

// MARK: - Private

private var onInteractionChanged: InteractionClosure? {
get {
let wrapper =
objc_getAssociatedObject(self, &icAssociationKey) as? ClosureWrapper
return wrapper?.closure
}
set(newValue) {
objc_setAssociatedObject(self,
&icAssociationKey,
ClosureWrapper(newValue),
.OBJC_ASSOCIATION_RETAIN)
}
}

}

extension UIViewController : Interaction {}

// Helpers

private var icAssociationKey: UInt8 = 0

private class ClosureWrapper {
var closure: InteractionClosure?

init(_ closure: InteractionClosure?) {
self.closure = closure
}
}

客户端类:

class LoginViewController: UIViewController {

// MARK: - Lifecycle

override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}

// MARK: - Private

private func setup() {
// ...

addOnInteractionChanged { [unowned self] (enabled) in
self.signInButton.enabled = enabled
self.activityIndicatorView.hidden = !enabled
}
}

}

在管理类中:

visibleViewController?.setInteractionEnabled(true)

关于ios - 协议(protocol)扩展中的 Swift 闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38072248/

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