most of the menu items are removed and a "Comment" is added
import SwiftUI
struct ContentView: View {
@State private var text = "Пример текста для проверки"
var body: some View {
VStack {
CustomTextViewRepresentable(text: $text, customMenuItems: [
UIMenuItem(title: "Custom Action", action: #selector(CustomTextView.customAction))
])
.frame(height: 200)
}
}
}
struct CustomTextViewRepresentable: UIViewRepresentable {
var text: Binding
var customMenuItems: [UIMenuItem]
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> CustomTextView {
let textView = CustomTextView()
textView.customMenuItems = customMenuItems
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ uiView: CustomTextView, context: Context) {
uiView.text = text.wrappedValue
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: CustomTextViewRepresentable
init(_ parent: CustomTextViewRepresentable) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
self.parent.text.wrappedValue = textView.text
}
}
}
class CustomTextView: UITextView {
var customMenuItems: [UIMenuItem] = []
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
let menu = UIMenuController.shared
let newInstanceItem = UIMenuItem(title: "Comment", action:#selector(commentThisText))
menu.menuItems = [newInstanceItem]
menu.update()
if action == #selector(copy(_:)) || action == #selector(selectAll(_:)) || action == #selector(commentThisText){
return true
}
return false
}
@objc func commentThisText() {
print ("RUNNNN")
}
override func buildMenu(with builder: UIMenuBuilder) {
super.buildMenu(with: builder)
for menuItem in customMenuItems {
let action = menuItem.action
let title = menuItem.title
let customAction = UIAction(title: title, image: nil, identifier: nil, discoverabilityTitle: nil, attributes: [], state: .off) { _ in
self.perform(action, with: nil)
}
let customMenuItem = UIMenuItem(title: title, action: action)
builder.insertChild(UIMenu(title: "", options: [], children: [customAction]), atStartOfMenu: .edit)
}
}
@objc func customAction() {
print("Custom Action")
}
}
Post
Replies
Boosts
Views
Activity
Thanx, very helpful