Skip to content

Instantly share code, notes, and snippets.

@SatoTakeshiX
Created July 20, 2023 15:02
Show Gist options
  • Save SatoTakeshiX/3bef366c4ad49fae0b9413a4fe51d903 to your computer and use it in GitHub Desktop.
Save SatoTakeshiX/3bef366c4ad49fae0b9413a4fe51d903 to your computer and use it in GitHub Desktop.
Edit Menu for UITextView
//
// TextEditorView.swift
// SelectableEditorView
//
// Created by satoutakeshi on 2023/07/15.
//
import SwiftUI
#if canImport(UIKit)
import UIKit
#else
import AppKit
#endif
struct TextEditorView: View {
@State var editText = "Hello World"
var body: some View {
TextEditor(editText: $editText)
.border(Color.red)
}
}
#if canImport(UIKit)
struct TextEditor: UIViewRepresentable {
typealias UIViewType = UITextView
typealias Coordinator = TextEditCoordinator
@Binding var editText: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isSelectable = true
textView.isEditable = true
textView.text = editText
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {}
func makeCoordinator() -> Coordinator {
return TextEditCoordinator()
}
}
final class TextEditCoordinator: NSObject, UITextViewDelegate {
func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
let string = NSString(string: textView.text)
print("selected string is '\(string.substring(with: range))'")
let customMenu = UIMenu(
title: "uimenue",
options: .displayAsPalette,
children: [
UIAction(title: "menuItem1") { _ in
print("menuItem1")
},
UIAction(title: "menuItem2") { _ in
print("menuItem2")
},
UIAction(title: "menuItem3") { _ in
print("menuItem3")
}
]
)
return UIMenu(children: suggestedActions + [customMenu])
}
}
#elseif canImport(AppKit) && !targetEnvironment(macCatalyst)
struct TextEditor: NSViewRepresentable {
typealias NSViewType = NSTextView
typealias Coordinator = TextEditCoordinator
@Binding var editText: String
func makeNSView(context: Context) -> NSTextView {
let textView = NSTextView()
textView.delegate = context.coordinator
textView.isSelectable = true
textView.isEditable = true
return textView
}
func updateNSView(_ nsView: NSTextView, context: Context) {}
func makeCoordinator() -> TextEditCoordinator {
TextEditCoordinator()
}
}
final class TextEditCoordinator: NSObject, NSTextViewDelegate {
func textView(_ view: NSTextView, menu: NSMenu, for event: NSEvent, at charIndex: Int) -> NSMenu? {
view.textStorage?.string
let item = NSMenuItem(title: "custome", action: nil, keyEquivalent: "ssss")
menu.addItem(item)
return menu
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment