showing custom menu on selection in UIWebView in iphone

后端 未结 2 1267
鱼传尺愫
鱼传尺愫 2020-12-07 13:14

I want to show 2 options like \"hi\" & \"bye\" when user completes selection on UIWebView.

I have added observer to my view controller as follows. But I don\'t k

2条回答
  •  失恋的感觉
    2020-12-07 13:55

    In swift:

    class ViewController: UIViewController {
        override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
    
            // add two custom menu items to the context menu of UIWebView (assuming in contenteditable mode)
            let menuItem1 = UIMenuItem(title: "Foo", action: #selector(ViewController.foo))
            let menuItem2 = UIMenuItem(title: "Bar", action: #selector(ViewController.bar))
            UIMenuController.sharedMenuController().menuItems = [menuItem1, menuItem2]
        }
    
        override func viewDidDisappear(animated: Bool) {
            super.viewDidAppear(animated)
            UIMenuController.sharedMenuController().menuItems = nil
        }
    
        override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
            if webView?.superview != nil {
                if action == #selector(ViewController.foo) || action == #selector(ViewController.bar) {
                    return true
                }
            }
    
            return super.canPerformAction(action, withSender: sender)
        }
    
        func foo() {
            print("foo")
        }
    
        func bar() {
            print("bar")
        }
    }
    

    Note: #selector is available in Swift 2.2.

提交回复
热议问题