在使用OC開(kāi)發(fā)時(shí),有個(gè)尷尬的操作,就是:
UIImage * settingsIcon = [UIImage imageNamed:@"settingsIcon"];
硬編碼的圖片名稱到處都是,當(dāng)你在Assets改動(dòng)圖片資源時(shí),這里就尷尬了,更尷尬的是你可能很多地方用到了這個(gè)圖片,不得不去一一改正。
在Swift里可能一切就變得簡(jiǎn)單了,因?yàn)橛辛?a target="_blank" rel="nofollow">R.swift,從此就不用為類似的事情擔(dān)心了:
//之前的寫(xiě)法
let settingsIcon = UIImage(named: "settings-icon")
//現(xiàn)在的寫(xiě)法
let settingsIcon = R.image.settingsIcon()
另外還有字體、資源文件、顏色、本地化字符串、Nibs、Storyboard等都可以以類似的形式出現(xiàn),一切都是自動(dòng)化生產(chǎn),改動(dòng)會(huì)重新編譯。
安裝是簡(jiǎn)單的,熟悉的方式,添加pod:pod 'R.swift'
這里有個(gè)小插曲,pod需要最新版本,要不然會(huì)報(bào)錯(cuò):
[!] 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
但是如果系統(tǒng)是macOS High Sierra,你升級(jí)pod時(shí)會(huì)發(fā)現(xiàn)這個(gè)錯(cuò)誤:
You don't have write permissions for the /usr/bin directory
這是因?yàn)樾孪到y(tǒng)修改了/usr/bin目錄的權(quán)限,即使你sudo,也沒(méi)有權(quán)限修改這個(gè)目錄,可以換一個(gè)目錄安裝pod:
sudo gem install -n /usr/local/bin cocoapods
好了,言歸正傳,接下來(lái)添加腳本命令"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT"

command+B編譯一下就可以在根目錄找到一個(gè)文件:R.generated.swift
然后把它拖到工程上,此時(shí)不要選中Copy items if needed選項(xiàng),然后就可以使用了(可以把*.generated.swift文件設(shè)置為忽略文件,防止版本沖突):
//使用圖片資源
self.imageV.image = R.image.wxb()
//使用本地文件
let file = R.file.testGeojson
//使用storyboard
let storyboard = R.storyboard.main()
//設(shè)置了重用字符串后,就可以這樣注冊(cè)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
}
還有不常用的自定義顏色,字體,國(guó)際化字符串等,都是同樣的用法,改變了本地資源時(shí)會(huì)重新編譯,問(wèn)題就會(huì)暴露出來(lái),這樣就可以及時(shí)解決,防止遺漏。