先来看下目前如果我们要使用资源文件时代码是如何调用的:
let icon = UIImage(named: "settings-icon") let font = UIFont(name: "San Francisco", size: 42) performSegueWithIdentifier("openSettings")这种通过传入字符串来获取资源有很大的潜在的风险:
先看下上面的逻辑用R.swift代码调用:
let icon = R.image.settingsIcon let font = R.font.sanFrancisco(size:42) performSegueWithIdentifier(R.segue.openSettings)R如何解决上面的问题:
//使用R.swift之前 let settingsIcon = UIImage(named: "settings-icon") let gradientBackground = UIImage(named: "gradient.jpg") //使用R.swift let settingsIcon = R.image.settingsIcon let gradientBackground = R.image.gradientJpg
//使用R.swift之前 let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialTabBarController = storyboard.instantiateInitialViewController() as? UITabBarController let settingsController = self.instantiateViewControllerWithIdentifier("settingsController") as? SettingsController //使用R.swift let storyboard = R.storyboard.main.instance let initialTabBarController = R.storyboard.main.initialViewController let settingsController = R.storyboard.main.settingsController //通过这个代码来校验运行时storyboard的图片是否都能被加载 // 只在debug模式下有效,会通过断言来提示 R.storyboard.main.validateImages() //在运行时校验所有的viewController能够被正常加载 mode.R.storyboard.main.validateViewControllers()
//使用R.swift之前 performSegueWithIdentifier("openSettings") //使用R.swift performSegueWithIdentifier(R.segue.openSettings)
//使用R.swift之前 let nameOfNib = "CustomView" let customViewNib = UINib(nibName: "CustomView", bundle: nil) let rootViews = customViewNib.instantiateWithOwner(nil, options: nil) let customView = rootViews[0] as? CustomView let viewControllerWithNib = CustomViewController(nibName: "CustomView", bundle: nil) //使用R.swift let nameOfNib = R.nib.customView.name let customViewNib = R.nib.customView let rootViews = R.nib.customView.instantiateWithOwner(nil, options: nil) let customView = R.nib.customView.firstView(nil, options: nil) let viewControllerWithNib = CustomViewController(nib: R.nib.customView)
//使用R.swift之前 let textCellNib = UINib(nibName: "TextCell", bundle: nil) tableView.registerNib(textCellNib, forCellReuseIdentifier: "TextCellIdentifier") //使用R.swift tableView.registerNib(R.nib.textCell) //cellForRowAtIndexPath中获取cell let textCell = tableView.dequeueReusableCellWithIdentifier(R.nib.textCell.reuseIdentifier, forIndexPath: indexPath)
//使用R.swift之前 let lightFontTitle = UIFont(name: "Acme-Light", size: 22) //使用R.swift let lightFontTitle = R.font.acmeLight(size: 22)
//使用R.swift之前 let jsonURL = NSBundle.mainBundle().URLForResource("seed-data", withExtension: "son") //使用R.swift let jsonURL = R.file.seedDataJson
其他同类型的第三方库有: Shark, Natalie , SwiftGen
R.swift的优势有:
强烈建议项目只支持稳定的iOS8,但是这个库确实支持iOS7
每当项目build时,R.swift开始运行。它会侦测工程文件里包含的资源文件,接着生成一个 R.generated.swift的文件。这个文件根据项目里的资源文件按照类型生成结构体。
因为R.swift是在每次项目编译时运行,所以配置和其他第三方库有些区别。这里单独写了一篇介绍Installation:如何安装R.swift