iOS: Determine if device language is Right to Left (RTL)

前端 未结 11 1855
后悔当初
后悔当初 2020-12-04 23:20

Is there a way to easily determine if the language the device is set to is right to left (RTL)?

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 00:18

    Rose Perrone is completely correct. However the use of dispatch_once in a getter for a simple boolean value - is really too much overhead. Unnecessary use of dispatch once. Because you will probably want to use that many times inside a layout or drawing function.

    So you have two faster options:

    + (BOOL)isRtl
    {
        static BOOL isRtl = NO;
        static BOOL isRtlFound = NO;
        if (!isRtlFound)
        { // This is "safe enough". Worst case is this code will be called twice in the app's lifecycle...
            isRtl = [NSLocale characterDirectionForLanguage:[NSBundle mainBundle].preferredLocalizations[0]] == NSLocaleLanguageDirectionRightToLeft;
            isRtlFound = YES;
        }
        return isRtl;
    }
    

    Or just cache it in a static variable, using the static constructor:

    static BOOL s_isRtl = NO;
    + initialize
    {
        s_isRtl = [NSLocale characterDirectionForLanguage:[NSBundle mainBundle].preferredLocalizations[0]] == NSLocaleLanguageDirectionRightToLeft;
    }
    

    Note that this will actually share the static variable between any class that uses this code.

提交回复
热议问题