swiftUi propertWrapper 自定义标记属性

上篇文章我们知道@Status  的作用了

那么我们也可以自己定义类似的这种标签。。

首先我们先来看下不使用属性标签,向导页面如何写

//
//  PropertyWrapperView.swift
//  learn_swiftUi
//
//  Created by liuan on 2020/9/4.
//  Copyright © 2020 liuan. All rights reserved.
//

import SwiftUI
extension UserDefaults{
    public enum Keys{
        static let hadSHowUserGuide = "hadSHowUserGuide"
    }
    var hasShowUserGuide: Bool{
        set{
            set(newValue,forKey: Keys.hadSHowUserGuide)
        }
        get{
            bool(forKey: Keys.hadSHowUserGuide)
        }
    }
}
struct PropertyWrapperView: View {
    @State private var showText = UserDefaults.standard.hasShowUserGuide ? "已经展示":"尚未展示"
    var body: some View {
        Button(action: {
            if(!UserDefaults.standard.hasShowUserGuide){
                UserDefaults.standard.hasShowUserGuide = true
                self.showText = "已经展示"
            }
        }){
            Text(self.showText)
        }
    }
}

struct PropertyWrapperView_Previews: PreviewProvider {
    static var previews: some View {
        PropertyWrapperView()
    }
}

第一次进来 现实尚未展示 ,点击后现实已经展示

如果改为标签呢

//
//  PropertyWrapperView.swift
//  learn_swiftUi
//
//  Created by liuan on 2020/9/4.
//  Copyright © 2020 liuan. All rights reserved.
//

import SwiftUI
//extension UserDefaults{
//    public enum Keys{
//        static let hadSHowUserGuide = "hadSHowUserGuide"
//    }
//    var hasShowUserGuide: Bool{
//        set{
//            set(newValue,forKey: Keys.hadSHowUserGuide)
//        }
//        get{
//            bool(forKey: Keys.hadSHowUserGuide)
//        }
//    }

//}
@propertyWrapper
struct UserDefaultsWrappler {
    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 {
    @UserDefaultsWrappler("hadShowUserGudie", defaultValue: false)
    static var hadSHownUserGudie: Bool
    
    @State private var showText = PropertyWrapperView.hadSHownUserGudie ? "已经展示":"尚未展示"
    var body: some View {
        Button(action: {
            if( !PropertyWrapperView.hadSHownUserGudie){
                 PropertyWrapperView.hadSHownUserGudie = true
                self.showText = "已经展示"
            }
        }){
            Text(self.showText)
        }
    }
}

struct PropertyWrapperView_Previews: PreviewProvider {
    static var previews: some View {
        PropertyWrapperView()
    }
}

 

你可能感兴趣的:(#,swiftUI)