marmelroy / Localize-Swift

Swift friendly localization and i18n with in-app language switching
MIT License
3.08k stars 330 forks source link

Updating UI with LCLLanguageChangeNotification #137

Closed Tulakshana closed 5 years ago

Tulakshana commented 5 years ago

Could you please share a sample code on how to update the UI when we receive LCLLanguageChangeNotification. I receive the notification but I only see the change when I re-launch the app. Below is the code I have so far.

import UIKit
import Localize_Swift

class BaseVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        updateLocalizedStrings()

        NotificationCenter.default.addObserver(self, selector: #selector(updateLocalizedStrings), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // MARK: -

    @objc func updateLocalizedStrings() {
        // Abstract method
    }
}

class AnotherVC: BaseVC {

    @IBOutlet private weak var languageValueLabel: UILabel!

    @objc func updateLocalizedStrings() {
        langaugeLabel.text = Constants.LABEL_LANGUAGE
    }
}

struct Constants {
    static let LABEL_LANGUAGE = "Language".localized()
}
Tulakshana commented 5 years ago

I was able to solve my problem by changing my static constant to a computed variable. The change is as below,

struct Constants {
    static var LABEL_LANGUAGE: String {
        return "Language".localized()
    }
}