简体   繁体   English

如何在 SwiftUI 中创建通用 PreferenceKey?

[英]How can I make a Generic PreferenceKey in SwiftUI?

I want make a Generic PreferenceKey , which I got 2 issues with my codes.我想做一个Generic PreferenceKey ,我的代码有 2 个问题。

First I need define () for T , for using normal type like String , Int as String() or Int() so I need memberwise initializer for T .首先,我需要为T定义() ,用于使用像StringInt作为String()Int()这样的普通类型,所以我需要T成员初始化程序。

Second Xcode complain that my PreferenceKey does not conform to Equatable , while I did it!第二个 Xcode 抱怨我的PreferenceKey不符合Equatable ,而我做到了! <T: Equatable> <T:平等的>

How can I solve this 2 issues?我该如何解决这两个问题? thanks谢谢


struct ContentView: View {
    
    @State private var stringOfText: String = "Hello, world!"
    
    var body: some View {
        
        Text(stringOfText)
            .preference(key: CustomPreferenceKey.self, value: stringOfText)
            .onPreferenceChange(CustomPreferenceKey.self) { newValue in print(newValue) }
        
        
    }
}

struct CustomPreferenceKey<T: Equatable>: PreferenceKey {
    
    static var defaultValue: T { get { return T() } }
    
    static func reduce(value: inout T, nextValue: () -> T) { value = nextValue() }
    
}

Here is a possible approach to move with.这是一种可能的移动方法。 Tested as worked with Xcode 12.4 / iOS 14.4经测试与 Xcode 12.4 / iOS 14.4 一起使用

protocol Initable {
    init()
}

extension String: Initable {
}

struct CustomPreferenceKey<T: Equatable & Initable>: PreferenceKey {
    typealias Value = T

    static var defaultValue: T { get { T() } }

    static func reduce(value: inout Value, nextValue: () -> Value) {
        value = nextValue()
    }
}

struct ContentView: View {

    @State private var stringOfText: String = "Hello, world!"

    var body: some View {

        Text(stringOfText)
            .preference(key: CustomPreferenceKey<String>.self, value: stringOfText)
            .onPreferenceChange(CustomPreferenceKey<String>.self) { newValue in print(newValue) }
    }
}

backup 备份

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM