R.Swift優雅加載資源文件


在新的項目中,接觸到了一個很不錯的框架R.swift,可以幫助更方便安全的使用資源文件,相信已經使用過的或者還沒有接觸過的,一旦使用過了解過它,會愛上這個框架工具!

一、R.swift特點

  • 當項目build之后,R.swift開始運行,也就是說添加完圖片等資源文件時,build一下,R.swift第三方庫就會設置好剛剛添加的資源.
  • 加入的資源文件在build后自動在R.generated.swift文件中按照類型生成結構體.
  • 強類型,不需要類型判斷和轉換,自動返回對應類型.
  • 支持了多種資源類型.
  • 避免了資源名稱拼寫錯誤.

 

二、安裝

  1. 添加pod 'R.swift'到你的Podfile文件中,緊接着運行pod install
  2. 打開工程文件,點擊工程文件名稱,選擇TARGETS,點擊Build Phases,在點擊左上角的“+”添加New Run Script Phas

  3. 腳本輸入"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT/R.generated.swift",input files 添加   $TEMP_DIR/rswift-lastrun,out files 添加 $SRCROOT/R.generated.swift

  4. 拖拽R.generated.swift文件到項目中.

 

三、具體使用

1. 圖片-images

原生寫法

let sIcon = UIImage(named: "settings-icon")

使用R.swift

func icon() -> UIImage? {
        switch self {
        case .sourceRegulator:
            return R.image.home_SourceRegulatory()
        case .regulation:
            return R.image.home_regulationIcon()
        case .broker:
            return R.image.home_brokerIcon()
        case .engine:
            return R.image.home_engineIcon()
        case .falseBroker:
            return R.image.home_falseBrokerIcon()
        case .spread:
            return R.image.home_spredIcon()
        }
    }

 

2. 文件-Files

原始寫法

let plistURL = Bundle.main.url(forResource: "Book", withExtension: "plist")
let jsonPath = Bundle.main.path(forResource: "data", ofType: "json")

使用R.swift后

let plistURL = R.file.bookPlist()
let jsonPath = R.file.DataJson.path()

 

3.字體-Fonts

原始用法

let lightFontTitle = UIFont(name: "chalkduster", size: 22)

使用R.swift

R.font.chalkduster(size: 35)

 

4.Localized strings

原始寫法

let welcomeMessage = NSLocalizedString("welcome.message", comment: "")
let settingsTitle = NSLocalizedString("title", tableName: "Settings", comment: "")

// Formatted strings
let welcomeName = String(format: NSLocalizedString("welcome.withName", comment: ""), locale: NSLocale.current, "Alice")

// Stringsdict files
let progress = String(format: NSLocalizedString("copy.progress", comment: ""), locale: NSLocale.current, 4, 23)

使用R.swift

// Localized strings are grouped per table (.strings file)
let welcomeMessage = R.string.localizable.welcomeMessage()
let settingsTitle = R.string.settings.title()

// Functions with parameters are generated for format strings
let welcomeName = R.string.localizable.welcomeWithName("Alice")

// Functions with named argument labels are generated for stringsdict keys
let progress = R.string.localizable.copyProgress(completed: 4, total: 23)

 

上面就是本人項目經常使用到的,當然還有其他的用法和用處,不過,通過R.swift已經大大的方便我們日常開發,希望大家在項目中盡早的使用R.swift這個第三方庫.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM