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

How to get localized validation messages? #6

Closed
jonsaw opened this issue Jun 27, 2022 · 2 comments
Closed

How to get localized validation messages? #6

jonsaw opened this issue Jun 27, 2022 · 2 comments

Comments

@jonsaw
Copy link

jonsaw commented Jun 27, 2022

I'm trying to setup a multilingual app with Localizable.strings. So far, the UI elements in SwiftUI all translate as expected. How do we get the validation messages to translate accordingly?

@jonsaw
Copy link
Author

jonsaw commented Jun 28, 2022

Got it to work (with extra steps).

extension LocalizedStringKey {
    var stringKey: String {
        let description = "\(self)"
        
        let components = description.components(separatedBy: "key: \"")
            .map { $0.components(separatedBy: "\",") }
        
        return components[1][0]
    }
    
    func stringValue(locale: Locale = .current) -> String {
        return .localizedString(for: self.stringKey, locale: locale)
    }
}

struct LoginView: View {
    @Environment(\.locale) var locale: Locale

    func trValidationMessage(_ message: String) -> some View {
        let localeMessage = LocalizedStringKey(message).stringValue(locale: locale)
        return Text(localeMessage).foregroundColor(Color.red).font(.caption)
    }

    var body: some View {
        TextField("Email", text: $viewModel.email)
            .validation(viewModel.emailValidation) { message in
                trValidationMessage(message)
            }
    }
}

@jonsaw
Copy link
Author

jonsaw commented Feb 18, 2023

With iOS 16, managed to get it to work simply by using String(localized:)

let emailLabel = String(localized: "Email")
let errorMessage = String(localized: "Valid \(emailLabel) required")

@jonsaw jonsaw closed this as completed Feb 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant