.strings and .stringsdict really work well. I donβt like any approaches to broadcasting the storyboard, they are too fragile, and it sucks that you need to finish the whole cycle again just because you added / removed / or changed something in the storyboard.
I have good results with the following approach:
- Use
.strings localization .strings for captions / subtitles / placeholders / texts in your storyboard objects. - Define a helper function in the base class of the
UIViewController (or category) that goes through your user interface and sets localizations on supported widgets using your keys in the storyboard.
I am calling a helper function in viewDidLoad . Here is an example:
static void translateLocalizableStringsInView( UIView* v ) { NSBundle* mainBundle = [NSBundle mainBundle]; UIView* view = v; if ( [view isKindOfClass:UILabel.class] ) { UILabel* label = (UILabel*)view; if ( label.text.length ) { NSString* localizedString = [mainBundle localizedStringForKey:label.text value:nil table:nil]; if ( localizedString.length ) { label.text = localizedString; } } } else if ( [view isKindOfClass:UITextField.class] ) { UITextField* textField = (UITextField*)view; if ( textField.text.length ) { NSString* localizedString = [mainBundle localizedStringForKey:textField.text value:nil table:nil]; if ( localizedString.length ) { textField.text = localizedString; } } if ( textField.placeholder.length ) { NSString* localizedString = [mainBundle localizedStringForKey:textField.placeholder value:nil table:nil]; if ( localizedString.length ) { textField.placeholder = localizedString; } } } else if ( [view isKindOfClass:UIButton.class] ) { UIButton* button = (UIButton*)view; NSString* title = [button titleForState:UIControlStateNormal]; if ( title.length ) { NSString* localizedString = [mainBundle localizedStringForKey:title value:nil table:nil]; if ( localizedString.length ) { [button setTitle:localizedString forState:UIControlStateNormal]; } } } else if ( [view isKindOfClass:UISegmentedControl.class] ) { UISegmentedControl* sc = (UISegmentedControl*)view; for ( NSUInteger i = 0; i < sc.numberOfSegments; ++i ) { NSString* title = [sc titleForSegmentAtIndex:i]; if ( title.length ) { NSString* localizedString = [mainBundle localizedStringForKey:title value:nil table:nil]; if ( localizedString.length ) { [sc setTitle:localizedString forSegmentAtIndex:i]; } } } } } @implementation UIViewController (LocalizableStrings) -(void)LT_translateLocalizableStringsInView { [self.view LT_iterateThroughAllSubviewsRecursively:YES usingBlock:^(UIView * _Nonnull view, BOOL * _Nonnull stop) { translateLocalizableStringsInView( view ); }]; if ( self.navigationItem.titleView ) { translateLocalizableStringsInView( self.navigationItem.titleView ); } }
source share