如何在textview的longPressGesture上添加自定义menuItem并在单击时调用该menuItems操作?

时间:2019-10-21 17:11:16

标签: swiftui

我需要在文本视图中长按以将“突出显示”添加为新的自定义菜单项。 我已经能够删除不需要的“查找”,但无法弄清楚如何添加额外的菜单项。

  1. 在我的SwiftUI代码中,CustomUITextView扩展了UITextView,
class CustomUITextView: UITextView {

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.cut(_:))  ||
            action  == Selector(("_define:")) ||
            action  == #selector(UIResponderStandardEditActions.paste(_:)) ||
            action  == Selector(("_promptForReplace:")){
            return false;
        }
        else {
            return super.canPerformAction(action, withSender: sender)
        }
    }
}
  1. 并且TextView符合UIViewRepresentable协议-
struct TextView : UIViewRepresentable {

    var contents: NSAttributedString

    func makeUIView(context: Context) -> CustomUITextView {
        let customTextView = CustomUITextView()
        customTextView.isEditable = false
        customTextView.isUserInteractionEnabled = true
        return customTextView
    }

    func updateUIView(_ uiView: CustomUITextView, context: Context) {
        uiView.attributedText = contents
    }
}
  1. 在Swift中,我知道添加自定义菜单项的代码就是这样-
    func addSpecialMenu() {
        let menuController = UIMenuController.shared
        var menuItem = [UIMenuItem]();
        let highlightMenuItem = UIMenuItem(title: "Highlight", action: #selector(onHighlightClicked));
        menuItem.append(highlightMenuItem);
        menuController.menuItems = menuItem;
    }

我尝试在longPressGesture上调用addSpecialMenu()。但是无法正常工作。 如何在SwiftUI中添加自定义菜单链接??

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试实现SwiftUI中存在的CustomMenu。

您这样声明:

Text("Includes hidden menu")
    .contextMenu {
        Button(action: { }) {
            HStack {
                Image(systemName: "trash")
                Text("Delete")
            }
        }
        Button(action: { }) {
            HStack {
                Image(systemName: "pencil.tip")
                Text("Highlight")
            }
        }
    }

长按它附加到的元素即可显示它:

ContextMenu