LoginSignup
4
7

More than 5 years have passed since last update.

[iOS] storyboard 上での多言語化対応と UITabBarController の各タブの title の多言語化対応

Last updated at Posted at 2017-04-27

多言語化対応の基本は、情報がいっぱいあるのでここでは紹介しません。

準備するもの

  • Localization した .strings ファイル

1. storyboard 上で多言語化対応する方法

準備はシンプルで、 UILabel などにキーをプロパティで指定できるようにするだけ。
準備ができたら storyboard 上から直接設定できます。

import UIKit

/**
 UILabel に多言語化対応プロパティを設定
 */
extension UILabel {
  @IBInspectable var localizedText:String {
    set(key){
      let textComps:[String] = key.components(separatedBy: ".")
      self.text = NSLocalizedString(textComps[1], tableName: textComps[0], comment: "")
    }
    get{
      return self.text!
    }
  }
}

/**
 UIButton に多言語化対応プロパティを設定
 */
extension UIButton {
  @IBInspectable var localizedText:String {
    set(key){
      let textComps:[String] = key.components(separatedBy: ".")
      let text = NSLocalizedString(textComps[1], tableName: textComps[0], comment: "")
      self.setTitle(text, for: .normal)
    }
    get{
      return self.titleLabel!.text!
    }
  }
}

/**
 Bar Button に多言語化対応プロパティを設定
 */
extension UIBarButtonItem {

  @IBInspectable var localizedTitle: String {
    set(key){
      let textComps:[String] = key.components(separatedBy: ".")
      self.title = NSLocalizedString(textComps[1], tableName: textComps[0], comment: "")
    }
    get{
      return self.title!
    }
  }
}

/**
 NavigationItem に多言語化対応プロパティを設定
 */
extension UINavigationItem {

  @IBInspectable var localizedTitle: String {
    set(key){
      let textComps:[String] = key.components(separatedBy: ".")
      self.title = NSLocalizedString(textComps[1], tableName: textComps[0], comment: "")
    }
    get{
      return self.title!
    }
  }
}

すると、 storyboard のユーティリティエリアにプロパティが追加されているので、 [ファイル名].[キー] の形式で指定できるようになります。

Screen Shot 2017-04-27 at 13.37.09.png

2. UITabBarController の各タブの title を多言語化対応する方法

こちらは、 storyboard 上から設定する方法がわからずコードで指定してます。
下記コードを、 UITabBarController 配下の各ページに追加します。

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.navigationController?.tabBarItem.title = NSLocalizedString("pageTitle", tableName: "pageFile", comment: "")
  }
4
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7