onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to declare commands in Xcode extensions #638

Open onmyway133 opened 4 years ago

onmyway133 commented 4 years ago

Use commandDefinitions in XCSourceEditorExtension.

import Foundation
import XcodeKit

class SourceEditorExtension: NSObject, XCSourceEditorExtension {
    func extensionDidFinishLaunching() {

    }

    var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] {
        func makeDef(
            _ className: String,
            _ commandName: String
        ) -> [XCSourceEditorCommandDefinitionKey: Any] {
            guard let bundleId = Bundle(for: type(of: self)).bundleIdentifier else { return [:] }

            return [
                XCSourceEditorCommandDefinitionKey.identifierKey: bundleId + className,
                XCSourceEditorCommandDefinitionKey.classNameKey: className,
                XCSourceEditorCommandDefinitionKey.nameKey: commandName
            ]
        }

        return [
            makeDef(TypeCommand.className(), "Type"),
            makeDef(ReloadCommand.className(), "Reload"),
        ]
    }
}

There is a weird crash that we can't seem to declare functions or use commandDefinitions, the workaround is to declare in plist

Read more

unnamedd commented 4 years ago

@onmyway133 there is a typo in the title:

- extenstions
+ extensions
onmyway133 commented 4 years ago

@unnamedd Fixed, thanks a lot ❤️