To create a macOS app using SwiftUI that captures the selected text, converts it to uppercase, and sets the clipboard to the modified text using the Shift-F13 key combo, follow these steps:
- Create a new SwiftUI macOS App project in Xcode.
- Replace the
ContentView.swift file with the following code:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Select text and press Shift-F13 to copy and convert to uppercase")
.padding()
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onReceive(NotificationCenter.default.publisher(for: .textCaptured), perform: { _ in
captureTextAndConvertToUppercase()
})
.keyboardShortcut("F13", modifiers: [.shift], action: {
NotificationCenter.default.post(name: .textCaptured, object: nil)
})
}
func captureTextAndConvertToUppercase() {
let pasteboard = NSPasteboard.general
let copiedText = pasteboard.string(forType: .string) ?? ""
let uppercaseText = copiedText.uppercased()
pasteboard.clearContents()
pasteboard.setString(uppercaseText, forType: .string)
}
}
extension Notification.Name {
static let textCaptured = Notification.Name("textCaptured")
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This code creates a simple SwiftUI view that displays instructions to the user. It listens for the Shift-F13 key combo with a keyboard shortcut and captures the selected text, converts it to uppercase, and sets the clipboard to the modified text when the key combo is pressed.
- Run the app and test the functionality by selecting text and pressing Shift-F13. The selected text should be copied to the clipboard and converted to uppercase.