Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SwiftUI support #4

Open
Truba opened this issue May 11, 2021 · 0 comments
Open

Add SwiftUI support #4

Truba opened this issue May 11, 2021 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@Truba
Copy link
Member

Truba commented May 11, 2021

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 }
    }
}
@Truba Truba added the enhancement New feature or request label May 11, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

7 participants