how to create Custom UIMenuController with only custom items other than default?

本小妞迷上赌 提交于 2019-12-06 06:13:44

问题


I have requirement to show menu items on uiwebview whenever user selects any text.

I have tried

let highlightMenuItem = UIMenuItem(title: "Highlight", action: #selector(ViewController.hightlight))

UIMenuController.sharedMenuController().menuItems = [highlightMenuItem]

but this only appends more menu item with default existing one. as this

Is there any way out to achieve this with only menu items Copy, Highlight and Note?


回答1:


You can achieve this by subclassing UIWebView and overriding canPerformAction (Swift 3). Then, all you need to do is return false for whichever actions you want disabled.

Example:

class EditedUIMenuWebView: UIWebView {

  override func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool {
    if action == #selector(cut(_:)) {
      return false
    }
    if action == #selector(paste(_:)) {
      return false
    }
    if action == #selector(select(_:)) {
      return false
    }
    if action == #selector(selectAll(_:)) {
      return false
    }
    ...

    return super.canPerformAction(action, withSender: sender)
  }

}

If you have any questions please ask!

Edit If you want to disable all actions but a few it may be easier to just return false in canPerformAction and return true for the ones you want like so:

override func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool {
   if action == #selector(copy(_:)) || action == #selector(customMethod(_:)) {
     return true
   }
   ...
   return false
 }


来源:https://stackoverflow.com/questions/37945518/how-to-create-custom-uimenucontroller-with-only-custom-items-other-than-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!