Created
June 10, 2016 03:25
-
-
Save wh1pch81n/f503185ac132671c7043df106f01ec2f to your computer and use it in GitHub Desktop.
In objective -c you can use [self class] to get the Class of an object. From there you can get the NSBundle. A smart man can use a macro when locating strings and make one such that [self class] is used to get the correct bundle. However, swift does not have macros. Below is a work around that does something similar.
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
import Foundation | |
/** | |
original macro | |
#define DHLocalizedString(KEY, TABLE, COMMENT) NSLocalizedStringWithDefaultValue(KEY, TABLE, [NSBundle mainBundle], NSLocalizedStringWithDefaultValue(KEY, TABLE, [NSBundle bundleForClass:[self class]]), COMMENT) | |
*/ | |
func getNameByRemovingPrefixPathAndExtension(name: String) -> String { | |
let url = NSURL(string: name)! | |
let className = url.URLByDeletingPathExtension!.lastPathComponent! | |
return className | |
} | |
func objectifySwiftSelector(sel: String) -> Selector { | |
return NSSelectorFromString(sel.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "()_")).reduce("", combine: +)) | |
} | |
func objectifySwiftSelector(sel: Selector) -> Selector { | |
return objectifySwiftSelector(NSStringFromSelector(sel)) | |
} | |
public func DHLocalizedStringFromTable(key: String, table: String, comment: String?, file: String = #file, funcName: String = #function) -> String { | |
let className = getNameByRemovingPrefixPathAndExtension(file) | |
for fw in NSBundle.allFrameworks() { | |
let frameworkName = getNameByRemovingPrefixPathAndExtension(fw.bundlePath) | |
print("\(frameworkName).\(className)") | |
guard let cls = NSClassFromString("\(frameworkName).\(className)") else { | |
continue | |
} | |
print(cls) | |
let cls2 = (cls as! NSObject.Type).init() | |
guard cls2.respondsToSelector(objectifySwiftSelector(funcName)) else { | |
continue | |
} | |
// class found and function that called it is a part of that class | |
let bundleOfClass = NSBundle(forClass: cls) | |
let frameworkLocalizedString = NSLocalizedString(key, tableName: table, bundle: bundleOfClass, value: key, comment: comment ?? "") | |
return NSLocalizedString(key, tableName: table, bundle: NSBundle.mainBundle(), value: frameworkLocalizedString, comment: comment ?? "") | |
} | |
return key | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment