使用R.swift管理项目资源

在使用OC开发时,有个尴尬的操作,就是:

UIImage * settingsIcon = [UIImage imageNamed:@"settingsIcon"];

硬编码的图片名称到处都是,当你在Assets改动图片资源时,这里就尴尬了,更尴尬的是你可能很多地方用到了这个图片,不得不去一一改正。

在Swift里可能一切就变得简单了,因为有了R.swift,从此就不用为类似的事情担心了:

//之前的写法
let settingsIcon = UIImage(named: "settings-icon")

//现在的写法
let settingsIcon = R.image.settingsIcon()

另外还有字体、资源文件、颜色、本地化字符串、Nibs、Storyboard等都可以以类似的形式出现,一切都是自动化生产,改动会重新编译。

安装是简单的,熟悉的方式,添加pod:pod 'R.swift'
这里有个小插曲,pod需要最新版本,要不然会报错:

[!] Error installing R.swift
[!] /usr/bin/curl -f -L -o /var/folders/6v/5vjcptpx6m34sjl4_f584pcr0000gn/T/d20180331-990-nkbxzj/file.zip https://github.com/mac-cain13/R.swift/releases/download/v4.0.0/rswift-4.0.0.zip --create-dirs --netrc-optional

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   606    0   606    0     0    432      0 --:--:--  0:00:01 --:--:--   432
  0     0    0     0    0     0      0      0 --:--:--  0:01:16 --:--:--     0curl: (7) Failed to connect to github-production-release-asset-2e65be.s3.amazonaws.com port 443: Operation timed out

但是如果系统是macOS High Sierra,你升级pod时会发现这个错误:

You don't have write permissions for the /usr/bin directory

这是因为新系统修改了/usr/bin目录的权限,即使你sudo,也没有权限修改这个目录,可以换一个目录安装pod:

sudo gem install -n /usr/local/bin cocoapods

好了,言归正传,接下来添加脚本命令"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT"


使用R.swift管理项目资源_第1张图片

command+B编译一下就可以在根目录找到一个文件:R.generated.swift
然后把它拖到工程上,此时不要选中Copy items if needed选项,然后就可以使用了(可以把*.generated.swift文件设置为忽略文件,防止版本冲突):

//使用图片资源
self.imageV.image = R.image.wxb()
//使用本地文件
let file = R.file.testGeojson
//使用storyboard
let storyboard = R.storyboard.main()
//设置了重用字符串后,就可以这样注册cell了
self.tableView.register(R.nib.qsTableViewCell)

//代理方法里
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.qsTableViewCell, for: indexPath)!
        return cell
    }

还有不常用的自定义颜色,字体,国际化字符串等,都是同样的用法,改变了本地资源时会重新编译,问题就会暴露出来,这样就可以及时解决,防止遗漏。

你可能感兴趣的:(使用R.swift管理项目资源)