【问题标题】:iOS UITextView don't localize properly in storyboardiOS UITextView 在情节提要中没有正确本地化
【发布时间】:2017-04-07 17:34:09
【问题描述】:

我有一个故事板,上面有一些文本视图。当我尝试本地化情节提要(创建 Storyboard.strings 文件)时,所有 UITextViews 根本不本地化。 UILabel 很好。

我的配置如下: 1 个带有 2 个 Storyboard.strings 文件的基本 Storyboard 文件 Storyboard Configuration

Storyboard.strings 文件还可以,毕竟它可以与 UILabels 一起使用: Storyboard.strings file

您找到解决此问题的方法了吗? 我正在使用 Xcode 8.3、Swift 3、iOS 10。

【问题讨论】:

    标签: swift3 storyboard uitextview


    【解决方案1】:

    您可以在 Xcode 中创建一个 IBOutlet 并在 didSet 函数中设置初始 UITextView 值。

    例如

    @IBOutlet var textView: UITextView {
        didSet {
            textView.text = NSLocalizedString("CUSTOM_LOCALISED_STRING", comment: "Comment.")
        }
    }
    

    【讨论】:

    • 我非常想在 Storyboard 中进行本地化。您的解决方案迫使我将本地化的某些部分存储在 Localizable.strings 中。
    【解决方案2】:

    我最终得到了这个解决方案:

    在 UIViewController 中,我可以访问我的 UITextView 对象并强制使用 Storyboard.strings 中的本地化文本。

    func fixTextViewStoryboardLocalization() {
        guard  storyboard != nil else {
            return // No need to fix it if storyboard is not presented
        }
        let storyboardName = storyboard!.value(forKey: "name") as! String
        for case let textView as UITextView in view.subviews {
            if let ident = textView.restorationIdentifier {
                textView.text = NSLocalizedString("\(ident).text", tableName: storyboardName, bundle: Bundle.main, value: "", comment: "")
            }
        }
    }
    

    创建一个自定义的 MyViewController(选择你想要的任何名称),在 viewDidLoad 中调用这个函数:

    class MyViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            fixTextViewStoryboardLocalization()
        }
    }
    

    确保故事板视图控制器来自 MyViewController 类: MyViewController custom class in Storyboard

    为了使上面的代码正常工作,我需要为我的 Storyboard 中的每个 UITextView 设置恢复 ID: UITextView Restoration ID

    最后一步 - 在 Storyboard.strings 中本地化文本视图:

    /* Class = "UITextView"; text = "Base text"; ObjectID = "MyTextView-Restoration-ID"; */
    "MyTextView-Restoration-ID.text" = "Localized text comes here";
    

    这适用于我所有故事板中的所有 UITextView。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多