---
layout:     post
title:      R.swift 的使用
subtitle:   在项目中引入 R.swift，更安全的获取资源
date:       2017-05-04
author:     BY
header-img: img/post-bg-swift2.jpg
catalog: true
tags:
    - iOS
    - Swift
    - 开源库
---


> 本文首次发布于 [BY Blog](http://qiubaiying.github.io), 作者 [@柏荧(BY)](http://github.com/qiubaiying) ,转载请保留原文链接.


# 什么是 R.swift

介绍 [R.swift](https://github.com/mac-cain13/R.swift) 前，我们先看看 R.swift 能做什么

通常，我们是基于 字符串 来获取资源，例如：图片、xib、或者是 segue

```swift
let myImage = UIImage(named: "myImage")
let myViewController = R.storyboard.main.myViewController()
```

使用 R.swfit，我们可以这样写

```swift
let myImage = R.image.myImage()
let viewController = R.storyboard.main.myViewController()

```

R.swift 通过扫描你的各种基于字符串命名的资源，创建一个使用类型来获取资源。

在保证类型安全的同时，也在自动补全的帮助下节省了大量的时间。

# 导入 R.swift

[R.swift](https://github.com/mac-cain13/R.swift) 开源在 github 上。

这里是导入的[视频教程](https://vimeo.com/122888912)

使用 CocoaPods 导入项目中

1. 添加 `pod 'R.swift'`到 Podfile 文件，然后运行 `pod install`
2. 添加一个 `New Run Script Phase`

	![](https://ww4.sinaimg.cn/large/006tKfTcgy1ff84sw06qxj30vm0hrq6s.jpg)
	
3. 将 `Run Script` 拖动到 `Check Pods Manifest.lock` 的下面，并且添加脚本 `"$PODS_ROOT/R.swift/rswift" "$SRCROOT/项目名称"`

	![](https://ww4.sinaimg.cn/large/006tNc79gy1ff853qjiucj30yp0kkn1b.jpg)
	
4. `Command+B` 编译项目，在项目代码目录下，会生成一个 `R.generated.swift` 的文件，将它拖如项目中

	>注意：不要勾选 `Copy items if needed` 选项，因为每次编译都会生成新的 `R.generated.swift` 文件，copy 的话，旧的 `R.generated.swift` 将不会被覆盖。

	![](https://ww4.sinaimg.cn/large/006tNc79gy1ff85epj1qpj30qj0hdn17.jpg)

>tip： 可以在添加 `.gitignore` 添加一行 `*.generated.swift` 忽略该文件，避免造成冲突

 
# 用法


导入完成后，就可以在使用 R.swift 了

 ![](https://github.com/mac-cain13/R.swift/raw/master/Documentation/Images/DemoUseImage.gif) 

关于 R.swift 的更多用法，可以 [看这里](https://github.com/mac-cain13/R.swift/blob/master/Documentation/Examples.md)。