Localize String in a project - poloteh/iOSRoadmapTutorial GitHub Wiki

A few ways to localize the string.

  1. Normal using NSLocalizedString(key: String, comment: String) and create Strings File
  2. Using Property List File(plist) and few extension.

Recommend using Property List file.

Easy to maintain, And can avoid build error in Strings File (missing a colon, etc..)


Easy way to maintain string to localized

  1. Create a class call Localizator
import Foundation
import UIKit
class Localizator {
    
    static let sharedInstance = Localizator()
    
    lazy var localizableDictionary: NSDictionary! = {
        if let path = Bundle.main.path(forResource: "Localizable", ofType: "plist") {
            return NSDictionary(contentsOfFile: path)
        }
        fatalError("Localizable file NOT found")
    }()
    
    func localize(string: String) -> String {
        guard let localizedString = (localizableDictionary.value(forKey: string) as AnyObject).value(forKey:"value") as? String else {
            
            assertionFailure("Missing translation for: \(string)") // App will crash when string value is not added in Property List(plist)
            return "**Missing \(string)"
        }
        return localizedString
       
    }
}

extension String {
    var localized: String {
        return Localizator.sharedInstance.localize(string: self)
    }
}

  1. Use enum in for your string to avoid any insertion mistake
enum localize{
    static let Accept  = "Accept".localized
    static let Please_Use_This_Message = "Please use this message".localized
   }
  1. Create Localizable.plist File and click the localize button in the File Inspector Tab
  1. Add your string value in the plist file in the Base, you can view the plist as source code and copy it to another language instead of retyping all the string.

Storyboard

For Storyboard, drag an outlet to code for easy assign the text and maintain. Additional code to subclass UILabel, create a class UILocalizedLabel. In storyboard change the custom class to UILocalizedLabel.

import Foundation
import UIKit

final class UILocalizedLabel: UILabel {
    override func awakeFromNib() {
        super.awakeFromNib()
        text = text?.localized
    }
}

Usage

label.text = localize.Accept // Accept接受 

Example

Example Project

Reference

Property List

String Extension