UIMenuController 注意事项 OC与swift4.0

UIMenuController  是什么?

简单来说 就是我们常看到的  Textfiled  textView  webView 上面 当你 长按的时候 会有 弹出一长串 复制 粘粘  类似于 qq聊天 对应的详细 你查看的时候 会有复制 转发 那个 view.


好 先来 OC

1. 是 让 添加  UIMenuController 的控件 成为 响应者 *

- (BOOL)canBecomeFirstResponder{

returnYES;

}

2 重点来了 必须实现下面俩方法 这俩方法 一般写在 UIMenuController 创建的类 里面

- (BOOL)canBecomeFirstResponder{

      return YES;

}

//不要急 这个方法里面的 俩个selector 是 创建 UIMenuItem 的两个方法  是 确保 这俩个方法 才会触发  能够点击  否则  其他的 都不触发

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{

if(action ==@selector(copy:) || action ==@selector(paste:) || action ==@selector(cut:)) {

        return YES; 

 }

          returnNO;

}

3.  UIMenuController  的创建

UIMenuController*menuVc = [UIMenuController sharedMenuController];

if(menuVc.isMenuVisible) { 

 [menuVc setMenuVisible:NO animated:YES];

 }

//self.frame 是你 需要添加 删除 粘贴  UIMenuController 的控件的frame self.superview 其父视图的 frame

 [menuVc setTargetRect:self.frame inView:self.superview];

//使  UIMenuController 可见

 [menuVc setMenuVisible:YES animated:YES];

//自定义 的 item 就是 自定义 粘粘啊 删除啊 还是 其他的item

UIMenuItem*item1 = [[UIMenuItem alloc] initWithTitle:@"item1"action:@selector(item1Click:)];

UIMenuItem*item2 = [[UIMenuItem alloc] initWithTitle:@"item2"action:@selector(item2Click:)]; 

//这个就是 把 item 放到 menuVC上

menuVc.menuItems = @[item1,item2];

最后 实现方法 menitems 方法就好了 方法里面 具体做什么 看自己业务 

注意  这个是 把  我们的 字符串 复制到 我们的硬件中 在其他地方可以粘粘

UIPasteboard*board = [UIPasteboardgeneral Pasteboard];

 board.string ="复制到手机硬件中";

综上  oc的 代码  封装的 label

#import"LXBLabel.h"

@implementationLXBLabel

- (instancetype)initWithFrame:(CGRect)frame{

self= [superinitWithFrame:frame];

if(self) {

 [selfsetup]; }returnself;

}

- (void)awakeFromNib{ [selfsetup];

}

- (void)setup{

self.userInteractionEnabled =YES;

 [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLabel)]];

}

- (void)clickLabel{ 

[self becomeFirstResponder];

UIMenuController*menuVc =[UIMenuController  sharedMenuController];// 控制好menu的显示与隐藏UIMenuController*menuVc = [UIMenuController sharedMenuController];

if(menuVc.isMenuVisible) { 

 [menuVc setMenuVisible:NO animated:YES]; 

 }

 [menuVc setTargetRect:self.frame inView:self.superview];

 [menuVc setMenuVisible:YES animated:YES];}

UIMenuItem*item1 = [[UIMenuItem alloc] initWithTitle:@"复制"action:@selector(copy:)];

UIMenuItem*item2 = [[UIMenuItem alloc] initWithTitle:@"粘粘"action:@selector(paste:)]; 

UIMenuItem*item2 = [[UIMenuItem alloc] initWithTitle:@"剪贴"action:@selector(cut:)];

menuVc.menuItems = @[item1,item2];


- (BOOL)canBecomeFirstResponder{

// 明确该控件可以成为第一响应者 returnYES;

}

// 该控件可以执行哪些动作

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{

if(action ==@selector(copy:) || action ==@selector(paste:) || action ==@selector(cut:)) {

returnYES;

 }

returnNO;

}

- (void)copy:(UIMenuController*)menu{

UIPasteboard*board = [UIPasteboardgeneral Pasteboard]; 

 board.string =self.text;

 }

- (void)paste:(UIMenuController*)menu{

UIPasteboard*board = [UIPasteboardgeneral Pasteboard];

self.text = board.string;


}- (void)cut:(UIMenuController*)menu{

 [self copy:menu];

self.text =nil;

}

@end



swfit  与 OC 类似 就是写法 不同

```//

//  headerView.swift

//  MENEDEMO

//

//  Created by wwt on 2018/6/6.

//  Copyright © 2018年 wwt. All rights reserved.

//

import UIKit

class headerView: UIView {

    var label :UILabel?

    override init(frame: CGRect) {

        super.init(frame: frame)


        label = UILabel.init(frame: CGRect.init(x: 5, y: 5, width: frame.width - 10, height: frame.height - 10))

        label?.text = "sadasdasdsad"


        label?.font = UIFont.systemFont(ofSize: 15)

        label?.textColor = UIColor.red

        label?.isUserInteractionEnabled = true

        let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))

        lpgr.minimumPressDuration = 0.5

        label?.addGestureRecognizer(lpgr)

        self.becomeFirstResponder()

        addSubview(label!)


    }



    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    /*

    // Only override draw() if you perform custom drawing.

    // An empty implementation adversely affects performance during animation.

    override func draw(_ rect: CGRect) {

        // Drawing code

    }

    */


    public lazy var menuController: UIMenuController = {


        return UIMenuController.shared

    }()

    lazy var copyMenuItem: UIMenuItem = {

        return UIMenuItem(title:"复制", action:#selector(copyMenuAction))

    }()

    lazy var pasteMenuItem: UIMenuItem = {

        return UIMenuItem(title:"粘贴", action:#selector(pasteMenuAction))

    }()


}

extension headerView {


    override var canBecomeFirstResponder: Bool {


        return true


    }


    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

        if [#selector(copyMenuAction), #selector(pasteMenuAction)].contains(action) {

            return true

        }

        return false

    }

    @objc func handleLongPress (_ recognizer: UILongPressGestureRecognizer){


      // if recognizer.state == .began {


            self.becomeFirstResponder()

            label?.becomeFirstResponder()

            menuController.menuItems = [copyMenuItem]

            menuController.setTargetRect((label?.frame)!, in: (label?.superview)!)

            menuController.setMenuVisible(true, animated: true)

  //      }


    }



    class func showAlert(_ t:String? = nil, message:String?,leftButtonTitle:String,rightButtonTitle:String? = nil, leftBtnSureClick:(() -> Void)? = nil, rightCancleBtnClick:(() -> Void)? = nil) {


        DispatchQueue.main.async(execute: { () -> Void in

            var title = t

            if title == nil {


                title = "";

            }


            let alertVC = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert);

            alertVC.addAction(UIAlertAction(title: leftButtonTitle, style: UIAlertActionStyle.default, handler: { (sure) -> Void in


                if leftBtnSureClick != nil {


                    leftBtnSureClick!();

                }


            }))

            if rightButtonTitle != nil {


                alertVC.addAction(UIAlertAction(title: rightButtonTitle, style: UIAlertActionStyle.default, handler: { (cancle) -> Void in


                    if rightCancleBtnClick != nil {


                        rightCancleBtnClick!();

                    }


                }))

            }



            let vc =  UIApplication.shared.keyWindow?.rootViewController;


            if vc != nil {


            }

            if ((vc?.presentedViewController) != nil) {

                vc?.presentedViewController!.present(alertVC, animated: true, completion: nil);

                return;


            }

            vc?.present(alertVC, animated: true, completion: nil);

        })

    }


    @objc func copyMenuAction() {

        headerView.showAlert("提示", message: "复制", leftButtonTitle: "是", rightButtonTitle: "否", leftBtnSureClick: {


        }) {


        }

    }

    @objc func pasteMenuAction (){

      headerView.showAlert(message: "提示", leftButtonTitle: "知道了")

    }

}

你可能感兴趣的:(UIMenuController 注意事项 OC与swift4.0)