iOS 应用动态语言切换实现

介绍如何在 iOS 应用中实现系统语言切换时,程序界面语言同步更新的功能。

实现原理:

  1. 监听系统语言变化通知: 应用需注册监听 NSCurrentLocaleDidChangeNotification 通知,该通知会在系统语言设置发生改变时发出。

  2. 语言资源本地化: 将不同语言版本的字符串、图片等资源进行本地化处理,例如使用 .strings 文件存储不同语言的字符串。

  3. 动态加载资源: 在收到系统语言变化通知后,根据当前语言环境加载对应的本地化资源,并更新应用界面。

代码示例 (Swift):

// 监听系统语言变化通知
NotificationCenter.default.addObserver(self, selector: #selector(languageChanged), name: NSLocale.currentLocaleDidChangeNotification, object: nil)

@objc func languageChanged() {
  // 获取当前语言代码
  let currentLanguageCode = Locale.current.languageCode 

  // 根据语言代码加载对应资源
  // ... 

  // 更新界面
  // ... 
}

注意事项:

  • 确保所有需要本地化的资源都已正确处理。
  • 在切换语言后,需要及时刷新界面,以显示最新的语言资源。
  • 对于部分特殊情况,例如用户自定义的语言设置,需要进行额外的处理。
zip
App-internationalization-master.zip 预估大小:47个文件
folder
App-internationalization-master 文件夹
folder
App_国际化Tests 文件夹
file
App____Tests.m 905B
file
Info.plist 733B
folder
App_国际化 文件夹
folder
Assets.xcassets 文件夹
folder
AppIcon.appiconset 文件夹
file
120x120.png 22KB
file
87x87.png 21KB
file
Contents.json 773B
file
120.png 22KB
file
58.png 20KB
file
80.png 21KB
file
180x180.png 24KB
file
Contents.json 62B
folder
LaunchImage.launchimage 文件夹
file
Contents.json 966B
file
1242x2208.png 50KB
file
640x1136.png 21KB
file
640x960.png 22KB
file
750x1334.png 28KB
file
main.m 340B
file
AppDelegate.h 283B
file
AppDelegate.m 2KB
folder
Base.lproj 文件夹
file
LaunchScreen.storyboard 2KB
file
Main.storyboard 2KB
folder
Internation 文件夹
file
ZQInternationStyle.h 348B
folder
zh-Hans.lproj 文件夹
file
ZQInternationString.strings 213B
file
ZQInternationViewController.m 1KB
folder
zh-Hant.lproj 文件夹
file
ZQInternationString.strings 211B
file
ZQInternationViewController.h 245B
folder
en.lproj 文件夹
file
ZQInternationString.strings 215B
file
.DS_Store 6KB
folder
zh-Hans.lproj 文件夹
file
LaunchScreen.strings 1B
file
InfoPlist.strings 170B
file
Main.strings 1B
folder
zh-Hant.lproj 文件夹
file
LaunchScreen.strings 1B
file
InfoPlist.strings 170B
file
Main.strings 1B
file
Info.plist 1KB
folder
en.lproj 文件夹
file
LaunchScreen.strings 1B
file
InfoPlist.strings 173B
file
Main.strings 1B
file
.DS_Store 6KB
folder
App_国际化.xcodeproj 文件夹
folder
project.xcworkspace 文件夹
file
contents.xcworkspacedata 173B
folder
xcuserdata 文件夹
folder
panfei.xcuserdatad 文件夹
file
UserInterfaceState.xcuserstate 23KB
file
project.pbxproj 24KB
folder
xcuserdata 文件夹
folder
panfei.xcuserdatad 文件夹
folder
xcschemes 文件夹
file
xcschememanagement.plist 336B
folder
xcdebugger 文件夹
file
Breakpoints_v2.xcbkptlist 91B
folder
Mak-er.xcuserdatad 文件夹
folder
xcschemes 文件夹
file
App_国际化.xcscheme 4KB
file
xcschememanagement.plist 665B
folder
App_国际化UITests 文件夹
file
App____UITests.m 1KB
file
Info.plist 733B
...
zip 文件大小:219.47KB