Skip to content

Instantly share code, notes, and snippets.

@OleksiiShvachenko
Created November 2, 2017 14:41
Show Gist options
  • Save OleksiiShvachenko/c7e45bafb2e4ee86e6cff5977e0b29fa to your computer and use it in GitHub Desktop.
Save OleksiiShvachenko/c7e45bafb2e4ee86e6cff5977e0b29fa to your computer and use it in GitHub Desktop.
AutoLocalize for stroryboards and xibs.
import UIKit
private func AutoLocalize(_ string: String?) -> String? {
guard let string = string else {
return nil
}
if string.hasPrefix("%") {
return NSLocalizedString(string, comment: "")
}
return string
}
extension UIViewController {
@objc func autoLocalize() {
if let tabBarController = self.tabBarController {
for viewController in tabBarController.viewControllers ?? [] {
if let tabBarItem = viewController.tabBarItem {
tabBarItem.title = AutoLocalize(tabBarItem.title)
}
}
}
let item = navigationItem
item.title = AutoLocalize(item.title)
item.prompt = AutoLocalize(item.prompt)
item.leftBarButtonItem?.title = AutoLocalize(item.leftBarButtonItem?.title)
item.rightBarButtonItem?.title = AutoLocalize(item.rightBarButtonItem?.title)
item.backBarButtonItem?.title = AutoLocalize(item.backBarButtonItem?.title)
view.autoLocalize()
}
}
extension UIView {
@objc func autoLocalize() {
for view in subviews {
view.autoLocalize()
}
}
}
extension UILabel {
override func autoLocalize() {
super.autoLocalize()
let localizedText = AutoLocalize(text)
if localizedText == text {
return
}
text = localizedText
}
}
extension UIButton {
override func autoLocalize() {
super.autoLocalize()
setTitle(AutoLocalize(title(for: .normal)), for: .normal)
setTitle(AutoLocalize(title(for: .highlighted)), for: .highlighted)
setTitle(AutoLocalize(title(for: .selected)), for: .selected)
setTitle(AutoLocalize(title(for: .disabled)), for: .disabled)
}
}
extension UISegmentedControl {
override func autoLocalize() {
super.autoLocalize()
for index in (0..<numberOfSegments) {
setTitle(AutoLocalize(titleForSegment(at: index)), forSegmentAt: index)
}
}
}
extension UITextField {
override func autoLocalize() {
super.autoLocalize()
text = AutoLocalize(text)
placeholder = AutoLocalize(placeholder)
}
}
extension UITextView {
override func autoLocalize() {
super.autoLocalize()
text = AutoLocalize(text)
}
}
extension UISearchBar {
override func autoLocalize() {
super.autoLocalize()
text = AutoLocalize(text)
placeholder = AutoLocalize(placeholder)
prompt = AutoLocalize(prompt)
if let scopeButtonTitles = self.scopeButtonTitles {
var translatedTitles = [String]()
for title in scopeButtonTitles {
translatedTitles.append(AutoLocalize(title) ?? "")
}
self.scopeButtonTitles = translatedTitles
}
}
}
extension UIToolbar {
override func autoLocalize() {
for item in items ?? [] {
item.title = AutoLocalize(item.title)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment