swift基础之propertyWrapper

原创
2021/04/19 18:02
阅读数 69

propertyWrapper示例

import SwiftUI

@propertyWrapper
struct UserDefaultsWrapper<T> {
    
    var key:String
    
    var defaultValue: T
    
    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }
    
    var wrappedValue:T {
        get {
            return UserDefaults.standard.value(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

struct PropertyWrapperView: View {
    
    @UserDefaultsWrapper("hadShowUserGuide", defaultValue: false)
    static var hadShowUserGuide: Bool
    
    
    @State private var showText = PropertyWrapperView.hadShowUserGuide ? "已经展示过" : "没有展示过"
    
    var body: some View {
        Button(action: {
            if (!PropertyWrapperView.hadShowUserGuide) {
                PropertyWrapperView.hadShowUserGuide = true
                self.showText = "已经展示过"
            }
        }) {
            Text(self.showText)
        }
    }
}

struct PropertyWrapperView_Previews: PreviewProvider {
    static var previews: some View {
        PropertyWrapperView()
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部