Runtime quickly implements iOS internationalization

Note: 1. This method is used when NSLocalizedString 2 is not written in advance during development. While this method can quickly meet the requirements of iOS internationalization, it is generally not recommended. 3. The Localizable. Strings file still needs to be configured

The controls that display text on the phone are almost the most frequent:

  • UILabel:setText:
  • UIButton: setTitle:forState:

The idea is to internationalize the title before the title is assigned to the control. In simple terms, override the setText: method of the control and internationalize the received text. This requirement can be implemented using the setTxt method of the Runtime switching system.

Copy

#import "UILabel+Language.h" #import <objc/runtime.h> @implementation UILabel (Language) + (void)load{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class class = [self class]; SEL setTitleSel = @selector(setText:); SEL setLanguageSel = @selector(setLanguageTitle:); Method setTitleMethod = class_getInstanceMethod(class, setTitleSel); Method setLanguageTitleMethod = class_getInstanceMethod(class, setLanguageSel); BOOL suc = class_addMethod(class, setTitleSel, method_getImplementation(setLanguageTitleMethod), method_getTypeEncoding(setLanguageTitleMethod)); if (suc) { class_replaceMethod(class, setLanguageSel, method_getImplementation(setTitleMethod), method_getTypeEncoding(setTitleMethod)); }else{ method_exchangeImplementations(setTitleMethod, setLanguageTitleMethod); }}); } - (void)setLanguageTitle:(NSString *)str{ [self setLanguageTitle:NSLocalizedString(str, nil)]; }Copy the code

Disadvantages: 1. For example, if the User enters the Chinese login, the interface will be automatically translated into login if the UITextfield Rumtime replacement method is used