swift -> UIMenuController (long press the pop-up black horizontal bar menu) modification and custom creation

 

 *****  Modified

 

For UITextField, the UIWebView system comes with "copy", "select", "share" and other menus after selecting a piece of text, and now it needs to be modified

 

Example: UITextField

 

    func myMenu() {
        print(textField.text(in: textField.selectedTextRange!))
         /* If it is a webView
         webView.evaluateJavaScript("getSelection().toString()", completionHandler: { (result, error) in
             if result != nil {
                 print("selecter:"+(result  as! String) );
             } else {
             
             }
         })
         */
    }
 
    var textField:UITextField!;
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        textField = UITextField(frame: CGRect(x: 20, y: 80, width: 100, height: 80));
        textField.text = "sdfassdf sdf sdf sdf s dfs f sd fds";
        self.view.addSubview(textField)
        
        //
        let menuItem1 = UIMenuItem(title: "My Menu", action: #selector(myMenu))
        UIMenuController.shared.menuItems = [menuItem1]
 

        
        
    }
    

 

 

Effect

 
 

 

 

********  Create

  

   //This sentence is very important, pop-up UIMenuController.shared can be displayed even if there is no input focus
    override var canBecomeFirstResponder: Bool{
        return true;
    }
    func showLongPress(sender:UILongPressGestureRecognizer){
        self.view.becomeFirstResponder()
        let menuController = UIMenuController.shared
        let item1 = UIMenuItem(title: "测试1", action: #selector(test))
        let item2 = UIMenuItem(title: "测试2", action: #selector(test))
        menuController.menuItems = [item1, item2]
        menuController.setTargetRect(self.view.bounds, in: self.view!)//where in: which view to display above/below
        menuController.setMenuVisible(true, animated: true)

    }

 


 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326178148&siteId=291194637