09.R-Swift-安全的资源组织方案forSwift

官方链接: https://github.com/mac-cain13/R.swift 参考文章:

http://swifter.tips/safe-resource/ https://www.jianshu.com/p/6234e6e79b15

场景

在项目中经常会遇到通过字符串进行的一些资源操作比如图片什么的,维护修改成本较高

  • 一般操作

let icon = UIImage(named: "settings-icon")
let font = UIFont(name: "San Francisco", size: 42)
let color = UIColor(named: "indictator highlight")
let viewController = CustomViewController(nibName: "CustomView", bundle: nil)
let string = String(format: NSLocalizedString("welcome.withName", comment: ""), locale: NSLocale.current, "Arthur Dent")
  • 使用R.Swift

let icon = R.image.settingsIcon()
let font = R.font.sanFrancisco(size: 42)
let color = R.color.indicatorHighlight()
let viewController = CustomViewController(nib: R.nib.customView)
let string = R.string.localizable.welcomeWithName("Arthur Dent")

是不是显得十分清爽

导入R.Swift

  • pod 'R.swift'

  • install完成后添加 New Run Script Phase

  • 添加脚本 "$PODS_ROOT/R.swift/rswift" generate "$SRCROOT"

  • Command+B编译一次后会在目录下生成一个R.generated.swift文件,将其拖入工程

一定不要选中Copy items if needed 因为每次编译都会重新生成该文件所以最好在.gitignore中添加忽略*.generated.swift

Last updated