Xcode8 開放了新的一個Extension:Xcode Source Editor Extension,可以讓我們自己開發(fā)Xcode 插件陷寝,但是目前開發(fā)的API 還比較少潜圃,但是也不妨礙我們了解和使用蜡豹。本文主要介紹如何使用Xcode Source Editor Extension 實現(xiàn)一個簡單的自動生成代碼的插件捂齐。
效果
實現(xiàn)
新建一個MacOS 宿主項目甘桑,再新建一個Target,類型為Xcode Source Editor Extension撵割,并且設置target的簽名和宿主App的簽名一致贿堰。
目錄結構
系統(tǒng)默認為我們生成SourceEditorCommand 文件,其中這個方法就當做主入口啡彬,當調用插件時會執(zhí)行這個方法羹与。但是只能獲取到當前編輯文件的內容,不能獲取整個工程庶灿。
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
// Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
if invocation.commandIdentifier == InsetCodeKey {
handleInsertCode(invocation: invocation)
}else{
NSWorkspace.shared.open(URL.init(fileURLWithPath: "/Applications/GenerateCode.app"))
}
completionHandler(nil)
}
核心代碼如下纵搁,大致邏輯是獲取當前輸入的key,根據(jù)提前錄入的Map往踢,查找對應Value腾誉,并且替換當前行內容。
func handleInsertCode(invocation: XCSourceEditorCommandInvocation){
let selection = invocation.buffer.selections.firstObject as! XCSourceTextRange
let totalLines = invocation.buffer.lines
let curIndex = selection.start.line
var curLineContent = totalLines[curIndex] as! String
let mapKey = curLineContent.trimmingCharacters(in: .whitespacesAndNewlines)
let map = SharedUserDefault.shared.mapping
if let value = map[mapKey] {
let arr = convertToLines(string: value)
var numberOfSpaceIndent = curLineContent.range(of: mapKey)!.lowerBound.encodedOffset
var indentStr = ""
while numberOfSpaceIndent > 0 {
indentStr = indentStr.appending(" ")
numberOfSpaceIndent -= 1
}
if arr.isEmpty{
return
}
if let range = curLineContent.range(of: mapKey){
curLineContent.replaceSubrange(range, with: arr[0])
totalLines[curIndex] = curLineContent
}
for i in 1..<arr.count{
let insetStr = indentStr + arr[i]
totalLines.insert(insetStr, at: curIndex + i)
}
}
}
錄入界面
在主工程中峻呕,創(chuàng)建錄入界面利职,整體是個NSTableView,展示保存好的Map瘦癌,雙擊某一行或者點擊添加按鈕猪贪,進入編輯頁面,主要用NSTextField 實現(xiàn)
全局保存的Map 存儲在UserDefaults 里讯私,但是宿主和擴展共享數(shù)據(jù)的話热押,需要suiteName 相同才行,需要在App Group 里設置相同的key斤寇。
測試
先運行主App桶癣,測試添加數(shù)據(jù)是否正常
運行插件,選擇Xcode抡驼,會出來一個灰色的Xcode鬼廓,隨便打開一個項目
輸入key肿仑,運行插件致盟,正確生成代碼。
也可以綁定快鍵鍵
使用
將app 拷入應用程序里尤慰,并且將設置里Xcode 擴展選上馏锡,重啟Xcode,就能在Editor 里使用啦
總結
插件主要參考了EasyCode伟端,站在了巨人的肩膀上杯道。但是目前EasyCode 好像Swift 不能用,因為媳婦開發(fā)用的純Swift责蝠,所以主要寫給她用的党巾,目前插件的功能還很簡單萎庭,但是基本可以使用了,后續(xù)可以繼續(xù)優(yōu)化齿拂!