製作一個Mac APP:XcodeExtension
作為一個iOS developer 突然想嘗試Mac開發,這是我第一個Mac APP
這個軟體目前包含以下功能
- ConvertFromCase 把選擇的下劃線內容變為駝峰
- DeleteEmptyLines 刪除選中的空行
- SortLines 排列選中的行
- JsonToModel 把Json資料轉成Swift模型,會把下劃線命名變為駝峰
如何使用
- 下載 最新的版本
- 解壓之後可以把應用移到應用程式中,方便下次使用!
- 開啟應用!
- 在安全與隱私設定中點仍要開啟
- 開啟的介面可以把Json資料轉成Swift模型,會把下劃線命名變為駝峰。在左邊放入Json,點選轉換。
- 在設定中選擇擴充套件,勾上這些功能。
- 開啟Xcode,在選單欄中Editor中就可以看到這些外掛
建立Cocoa APP
在建立工程的時候選擇macOS->Cocoa App

Xcode 外掛
Apple在Xcode8的時候引入外掛開發,雖然很弱雞,但是還是能實現部分功能的。
建立target
新建target 選擇macOS->Xcode Source Editor Extension

XcodeKit
建立名字 DeleteEmptyLines
的target會有以下檔案

-
info.plist
檔案中是target的配置

XCSourceEditorCommandName 這裡可以改名字
-
SourceEditorExtension.swift
中實現了XCSourceEditorExtension
都是可選方法-
extensionDidFinishLaunching
外掛在啟動的時候執行 -
commandDefinitions
這個地方會覆蓋info.plist
的設定
-
-
SourceEditorCommand.swift
中實現了XCSourceEditorCommand
-
perform
一旦觸發外掛的命名,就會觸發此方法,引數invocation:XCSourceEditorCommandInvocation
包含了文字快取的內容buff
-
buff.selections
就是選中文字的範圍,buff.lines
是每一行的文字,我們可以改變它來改變文字的內容
-
實現第一個外掛-刪除所選程式碼中的空行
增加以下程式碼
extension XCSourceEditorCommandInvocation { var selections: [XCSourceTextRange] { return buffer.selections as! [XCSourceTextRange] } func deleteEmptyLines() { selections.forEach { (selection) in let start = selection.startLine let end = selection.endLine let emptyIndexs = (start...end) .filter({ (index) -> Bool in (buffer.lines[index] as! String).match(regular: "^\\s*$") }) buffer.lines.removeObjects(at: IndexSet(emptyIndexs)) } } } extension String { func match(regular: String) -> Bool { return range(of: regular, options: .regularExpression) != nil } } extension XCSourceTextRange { var startLine: Int { return start.line } var endLine: Int { return end.line - (end.column == 0 ? 1 : 0) } } 複製程式碼
在 SourceEditorCommand
中修改 perform
方法
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) { defer { completionHandler(nil) } invocation.deleteEmptyLines() } 複製程式碼
測試
選擇要測試的target

選擇Xcode

會有一黑色的Xcode用於測試

任意開啟一個專案
- 選中一段程式碼
- 在選單欄選擇 Editor-> DeleteEmptyLines -> Source Editor Command
如果不是這個命名就這樣找: Editor —> Extension bundle display name -> command name
Json轉model介面
在iOS開發的時候,由於後臺返回的資料用的是下劃線命名法,而APP使用的是駝峰命名法,於是我做了一個介面來處理。
介面
選擇工程中的 Main.storyboard
,在View Controller中拖入兩個TextView,和一個button

調整控制元件的樣式,加上佈局約束。寫成喜歡的樣式-,-

繫結這些控制元件到ViewController程式碼中

程式碼
在 convert
方法中寫轉換的程式碼就行了,程式碼較長放在文章末尾的GitHub連結。
有一個細節需要注意,macOS在輸入引號的時候會自動轉為Json不能解析的格式,所以需要設定 NSTextView
的 isAutomaticQuoteSubstitutionEnabled
為 false