How to know if language is right-to-left in SwiftUI?
Asked Answered
A

1

5

I'm building an App using SwiftUI, and I'm using a pointing hand SF Symbol, the issue is that to localize the App for right-to-left languages this symbol doesn't make sense, I want to add a condition to change it when the language is right-to-left.

How to know if the local language is right-to-left in SwiftUI?

Here's the code:

struct MyView: View {
    var body: some View {
        HStack {
            Spacer()
            Text("SWIPE")
                .font(.system(.headline, design: .serif))
            Image(systemName: localizedSymbol)
                .font(.title2)
        }
    }
    
    var localizedSymbol: String {
        var leftToRight = true // How to get this property
        return leftToRight ? "hand.point.right" : "hand.point.left"
    }
}

I did found this article, but how can I access UIView, I could use UIViewRepresentable with UIImage, but seems too complex and unreadable for such task. https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/SupportingRight-To-LeftLanguages/SupportingRight-To-LeftLanguages.html

Allegedly answered 10/5, 2021 at 16:24 Comment(0)
T
15

Here is Locale based approach:

guard let language = Locale.current.languageCode else { return }
let direction = Locale.characterDirection(forLanguage: language)
switch direction {
    case .leftToRight:
        print("do something here")
    case .rightToLeft:
        print("do something here")
    // ... others if needed
    default:
        print("do something here")
}
Trudey answered 10/5, 2021 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.