做为一个iOS developer 忽然想尝试Mac开发,这是我第一个Mac APPgit
这个软件目前包含如下功能github
在建立工程的时候选择macOS->Cocoa Appswift
Apple在Xcode8的时候引入插件开发,虽然很弱鸡,可是仍是能实现部分功能的。api
新建target 选择macOS->Xcode Source Editor Extension缓存
建立名字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
方法ui
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) {
defer { completionHandler(nil) }
invocation.deleteEmptyLines()
}
复制代码
选择要测试的targetspa
若是不是这个命名就这样找: Editor —> Extension bundle display name -> command name
在iOS开发的时候,因为后台返回的数据用的是下划线命名法,而APP使用的是驼峰命名法,因而我作了一个界面来处理。
选择工程中的Main.storyboard
,在View Controller中拖入两个TextView,和一个button
调整控件的样式,加上布局约束。写成喜欢的样式-,-
绑定这些控件到ViewController代码中
在convert
方法中写转换的代码就好了,代码较长放在文章末尾的GitHub连接。
有一个细节须要注意,macOS在输入引号的时候会自动转为Json不能解析的格式,因此须要设置
NSTextView
的isAutomaticQuoteSubstitutionEnabled
为false
在左边放入Json,点击转换。
本文版权属于再惠研发团队,欢迎转载,转载请保留出处。@白尔摩斯