Created
October 31, 2017 23:50
-
-
Save quocnb/35e7c75a623300f2ac612f87cb82a1bb to your computer and use it in GitHub Desktop.
#iOS#Swift Localized String For Xib File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol Localizable { | |
func localize() | |
} | |
public extension Localizable { | |
public func localize(_ string: String?) -> String? { | |
guard let term = string, term.hasPrefix("@") else { | |
return string | |
} | |
guard !term.hasPrefix("@@") else { | |
return term.substring(from: term.index(after: term.startIndex)) | |
} | |
return NSLocalizedString(term.substring(from: term.index(after: term.startIndex)), comment: "") | |
} | |
public func localize(_ string: String?, _ setter: (String?) -> Void) { | |
setter(localize(string)) | |
} | |
public func localize(_ getter: (UIControlState) -> String?, _ setter: (String?, UIControlState) -> Void) { | |
setter(localize(getter(.normal)), .normal) | |
setter(localize(getter(.selected)), .selected) | |
setter(localize(getter(.highlighted)), .highlighted) | |
setter(localize(getter(.disabled)), .disabled) | |
} | |
} | |
extension UIView: Localizable { | |
public func localize() { | |
subviews.forEach { $0.localize() } | |
} | |
} | |
public extension UILabel { | |
public override func localize() { | |
super.localize() | |
localize(text) { text = $0 } | |
} | |
} | |
public extension UIButton { | |
public override func localize() { | |
super.localize() | |
localize(title(for:), setTitle(_:for:)) | |
} | |
} | |
extension UIBarItem: Localizable { | |
public func localize() { | |
localize(title) { title = $0 } | |
} | |
} | |
public extension UIBarButtonItem { | |
public override func localize() { | |
super.localize() | |
customView?.localize() | |
} | |
} | |
extension UINavigationItem: Localizable { | |
public func localize() { | |
localize(title) { title = $0 } | |
localize(prompt) { prompt = $0 } | |
titleView?.localize() | |
leftBarButtonItems?.forEach { $0.localize() } | |
rightBarButtonItems?.forEach { $0.localize() } | |
} | |
} | |
extension UIViewController: Localizable { | |
public func localize() { | |
localize(title) { title = $0 } | |
navigationItem.localize() | |
tabBarItem?.localize() | |
view.localize() | |
} | |
} | |
// Create Localizable.strings files for support multi language | |
// In xib file, if you want to set localized text = "This is text" to the button, input in the button title text "@This is text", it will auto localized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment