先來看下目前如果我們要使用資源文件時代碼是如何調(diào)用的:
let icon = UIImage(named: "settings-icon") let font = UIFont(name: "San Francisco", size: 42) performSegueWithIdentifier("openSettings")這種通過傳入字符串來獲取資源有很大的潛在的風(fēng)險:
先看下上面的邏輯用R.swift代碼調(diào)用:
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的優(yōu)勢有:
強烈建議項目只支持穩(wěn)定的iOS8,但是這個庫確實支持iOS7
每當項目build時,R.swift開始運行。它會偵測工程文件里包含的資源文件,接著生成一個 R.generated.swift的文件。這個文件根據(jù)項目里的資源文件按照類型生成結(jié)構(gòu)體。
因為R.swift是在每次項目編譯時運行,所以配置和其他第三方庫有些區(qū)別。這里單獨寫了一篇介紹Installation:如何安裝R.swift