廣告
Swift iOS開發小書 ,幫你快速上手開發 www.ituring.com.cn/book/2413
正文
你建立了一個迷幻的View,想要向全世界共享它。怎麼辦?cocoapods可以幫忙。
##建立一個工程,其中有你需要分享的程式碼
首先,我們建立這樣的一個Single View App。新增一個swift檔案(名字為:FantasticView.swift),內容為:
import UIKit
class FantasticView : UIView {
let colors : [UIColor] = [.red, .orange, .yellow, .green, .blue, .purple]
var colorCounter = 0
override init(frame: CGRect) {
super.init(frame: frame)
let scheduledColorChanged = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { (timer) in //1
UIView.animate(withDuration: 2.0) { //2
self.layer.backgroundColor = self.colors[self.colorCounter % 6].cgColor //3
self.colorCounter+=1 //4
}
}
scheduledColorChanged.fire()
// The Main Stuff
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// You don't need to implement this
}
}複製程式碼
然後編寫程式碼,做一個demo,把這個檢視用起來,程式碼覆蓋ViewController.swift:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fantasticView = FantasticView(frame: self.view.bounds)
self.view.addSubview(fantasticView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}複製程式碼
跑起來後,你可以看到一個變化顏色的檢視,說明類FantasticView正常工作了。這個檔案,就是我們想要分享的。
接下來,如果想要CocoaPods幫忙,給建立一個檔案.podspec檔案,並把這個檔案傳遞到CocoaPods網站上。此檔案會告訴想要使用此pod的人如下資訊:
1. 這個pod叫什麼名字
2. 版本號多少
3. 程式碼包括哪些檔案
4. 檔案在哪裡複製程式碼
等等必要的和描述性的資訊。
建立一個github倉庫,推送檔案,並做一個release
檔案我們會放到github倉庫上,因此,一個github的賬號是必要的。倉庫需要建立一個release,因為podspec會引用此release。我的相關資訊:
- github賬號是1000copy
- 用於儲存分享程式碼的倉庫名字:FantasticView
你需要在如下的命令和操作中,替代為你的對應資訊。首先
- 建立一個倉庫,命名為FantasticView
在命令列內導航到你的工程目錄,執行命令以便把程式碼傳遞到github倉庫內
git init
git add .
git commit -m "init"
git remote add origin
git push -u origin master- 在github上,對此倉庫做一個release,版本號設定為0.1.0,這個號碼值會在podspec檔案內引用的。
終於,我們可以建立一個pod了。
依然需要在命令列內,導航到你的工程目錄,然後:
touch FantasticView.podspec複製程式碼
貼上內容為:
Pod::Spec.new do |s|
s.name = 'FantasticView'
s.version = '0.1.0'
s.summary = '一些屁話'
s.description = <<-DESC
更多行
行的
屁話
DESC
s.homepage = 'https://github.com/1000copy/FantasticView'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '1000copy' => '1000copy@gmail.com' }
s.source = { :git => 'https://github.com/1000copy/FantasticView.git', :tag => s.version.to_s }
s.ios.deployment_target = '10.0'
s.source_files = 'FantasticView/*'
end複製程式碼
其中特別重要的是s.name ,s.version , s.source ,s.source_files,沒有這些資訊,釋出pod是不可能的。
接著執行命令,檢查此podspec是否正確:
pod lib lint複製程式碼
釋出
執行命令釋出,首先註冊你的郵件,然後推送podspec。
pod trunk register 1000copy@gmail.com
pod trunk push FantasticView.podspec複製程式碼
注意,註冊郵件後,cocoapods會傳送一個郵件給你,你點選裡面的確認連結,即可生效。
你應該看到如下的資訊反饋:
? Congrats
? FantasticView (0.1.0) successfully published
? August 16th, 06:03
? https://cocoapods.org/pods/FantasticView
? Tell your friends!複製程式碼
現在,你可以像其他pod一樣使用FantasticView了。