gpt4 book ai didi

swift - 在 Swift 5.1 Property Wrappers 中访问 self

转载 作者:行者123 更新时间:2023-11-28 07:20:59 24 4
gpt4 key购买 nike

我想创建一个使我的 UICollectionViewLayout 布局无效的属性包装器。

因此我创建了这个属性包装器

@propertyWrapper
class LayoutInvalidating {
private let layout: UICollectionViewLayout

init(layout: UICollectionViewLayout) {
self.layout = layout
self.wrappedValue = layout
}

var wrappedValue: UICollectionViewLayout {
didSet {
self.layout.invalidateLayout()
}
}
}

那么我想按如下方式使用它

final class VehicleControlsCollectionViewLayout: UICollectionViewLayout {
@LayoutInvalidating(layout: self) // self is not alive
public var itemSize: CGSize = .init(width: 70, height: 70)
}

每次设置属性时,我都想调用 self.invalidateLayout()。有什么想法可以在 self 存在时访问它吗?

最佳答案

不幸的是,无法将 self 添加到 @propertyWrapperinit - 此属性是在 self 创建期间创建的

将来有可能-看proposal (在包装器类型中引用封闭的“self”)。


如果您正在寻找某种解决方法,您可以考虑将函数添加到您的属性包装器并在您的类中初始化之后调用此函数:

@propertyWrapper
class LayoutInvalidating<Value> {
private var layout: UICollectionViewLayout?

init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}

func configure(with layout: UICollectionViewLayout?) {
self.layout = layout
}

var wrappedValue: Value {
didSet {
layout?.invalidateLayout()
}
}
}

final class VehicleControlsCollectionViewLayout: UICollectionViewLayout {
@LayoutInvalidating
public var itemSize: CGSize = .init(width: 70, height: 70)

override init() {
super.init()
_itemSize.configure(with: self)
}
}

关于swift - 在 Swift 5.1 Property Wrappers 中访问 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079611/

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