class CustomPDFView: PDFView {
var toolMode: ToolMode = .none
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
switch toolMode {
case .comment, .highlight, .translate :
return false
default :
if action == #selector(copy(_:)) || action == #selector(selectAll(_:)) {
return true
}
return false
}
}
}
class originlaView: UIViewController {
override func buildMenu(with builder: UIMenuBuilder) {
super.buildMenu(with: builder)
builder.remove(menu: .share)
//builder.remove(menu: .lookup)
}
}
I cleared the 'lookup' menu, but the 'translate', 'searchWeb' menus were all cleared.
I would like to keep the 'translate' menu, but it seems to be included in the 'lookup' menu.
I also tried clearing 'lookup' and 'searchWeb' separately in 'canPerformAction()', but that didn't work.
The following implementation of buildMenu
will result in the "Look Up" and "Search Web" menus no longer appearing. Comments in the code explain how this works.
override func buildMenu(with builder: any UIMenuBuilder) {
// Start by updating the Lookup menu.
// The Lookup menu actually consists of the "Find Selection", "Look Up", and "Translate" commands.
// The "Search Web" menu gets added to the Lookup menu after this buildMenu is called.
// The goal is to show only the "Translate" menu. "Find Selection" is not normally shown so we only need
// to remove the "Look Up" menu and somehow prevent the "Search Web" menu from being added automatically.
// The following code locates the "Translate" command from within the "Lookup" menu. An updated array of
// child commands is returned consisting of just the "Translate" command. As a side effect of returning
// the modified list of children, the "Search Web" menu is no longer added. This achieves the goal of only
// showing the "Translate" menu.
builder.replaceChildren(ofMenu: .lookup) { oldChildren in
// Enumerate the original child commands of the Lookup menu. As of this writing this will include:
// "Find Selection"
// "Look Up"
// "Translate"
for menuElement in oldChildren {
if let command = menuElement as? UICommand {
if command.action == NSSelectorFromString("_translate:") {
// This is the "Translate" command. Return just this command as the updated children of
// the "Lookup" menu.
return [command]
}
}
}
// If the "Translate" command isn't found, return the original children as a fallback. This results
// in the standard menu being shown.
return oldChildren
}
// Also remove the Share menu
builder.remove(menu: .share)
}