Last active
June 9, 2020 13:03
-
-
Save fl034/5a7d8d33d6681d9ceedb8448561750df to your computer and use it in GitHub Desktop.
XIB + Storyboard Localization
This file contains hidden or 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
// | |
// Localization.swift | |
// | |
// | |
// Created by Frank Lehmann on 03.07.19. | |
// Based on: https://medium.com/@mario.negro.martin/easy-xib-and-storyboard-localization-b2794c69c9db | |
// | |
import UIKit | |
public extension String { | |
var localized: String { NSLocalizedString(self, comment: "") } | |
var loc: String { localized } | |
} | |
protocol XIBLocalizable { | |
var xibStringKey: String? { get set } | |
} | |
extension UILabel: XIBLocalizable { | |
private static var _uppercaseStore = [String:Bool]() | |
private static var _xibStringStore = [String:String]() | |
private func reloadText() { | |
let _text = (xibStringKey ?? text)?.localized | |
text = isUppercased ? _text?.uppercased() : _text | |
} | |
@IBInspectable | |
var isUppercased: Bool { | |
get { | |
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) | |
return UILabel._uppercaseStore[tmpAddress] ?? false | |
} | |
set { | |
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) | |
UILabel._uppercaseStore[tmpAddress] = newValue | |
reloadText() | |
} | |
} | |
@IBInspectable | |
var xibStringKey: String? { | |
get { | |
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) | |
return UILabel._xibStringStore[tmpAddress] | |
} | |
set { | |
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) | |
UILabel._xibStringStore[tmpAddress] = newValue | |
reloadText() | |
} | |
} | |
} | |
extension UIButton: XIBLocalizable { | |
@IBInspectable | |
var xibStringKey: String? { | |
get { return nil } | |
set { | |
setTitle(newValue?.localized, for: .normal) | |
} | |
} | |
} | |
extension UIBarButtonItem: XIBLocalizable { | |
@IBInspectable | |
var xibStringKey: String? { | |
get { return nil } | |
set { | |
title = newValue?.localized | |
} | |
} | |
} | |
extension UITextField: XIBLocalizable { | |
@IBInspectable | |
var xibStringKey: String? { | |
get { return nil } | |
set { | |
text = newValue?.localized | |
} | |
} | |
@IBInspectable | |
var xibPlaceholderKey: String? { | |
get { return nil } | |
set { | |
placeholder = newValue?.localized | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment