Skip to content

Add SwiftUI support #4

Closed
Closed
@Truba

Description

@Truba

We can add something in the lines of:

public struct LocText<S>: View where S: StringsProtocol, S.RawValue == String {
    
    public let key: S
    
    @Environment(\.locale) var locale: Locale
    
    public var body: some View {
        return Text(NSLocalizedString(key.rawValue, tableName: locale.identifier, comment: ""))
    }
}

public extension LocText where S == Strings {
    
    init(_ key: Strings) {
        self.key = key
    }
    
}

struct LocText_Library: LibraryContentProvider {
    var views: [LibraryItem] {
        [
            LibraryItem(LocText(.todo), title: "Localized Text", category: .control)
        ]
    }
}

struct CustomLocaleModifier: ViewModifier {

    @State var locale: Locale = Locale(identifier: "en")

    func body(content: Content) -> some View {
        content
            .environment(\.customLocale, locale)
            .onPreferenceChange(CustomLocaleKey.self) { value in
                locale = value
            }
    }
}

struct CustomLocaleKey: EnvironmentKey, PreferenceKey {

    static var defaultValue: Locale = Locale(identifier: "en")

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

extension EnvironmentValues {
    var customLocale: Locale {
        get { self[CustomLocaleKey.self] }
        set { self[CustomLocaleKey.self] = newValue }
    }
}

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions