iOS Pasteboard详解(复制, 粘贴)

2019-01-03  本文已影响0人  浅宇落

在项目中UIPasteboard的用途

下面我们就以复制图片为例

效果图1
效果图2
@interface CopyView ()

@property (strong, nonatomic) UIImageView* img1;
@property (strong, nonatomic) UIImageView* img2;

@end
@implementation CopyView

-(UIImageView *)img1{
    if (_img1 == nil) {
        _img1 = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 100.0f, 100.0f)];
        _img1.image = [UIImage imageNamed:@"赵雅芝"];
    }
    return _img1;
}

-(UIImageView *)img2{
    if (_img2 == nil) {
        _img2 = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.img1.frame)+50.0f, 0.0f, 100.0f, 100.0f)];
        _img2.backgroundColor = [UIColor lightGrayColor];
    }
    return _img2;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.img1];
        [self addSubview:self.img2];
    }
    return self;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    NSArray* methodNameArr = @[@"copy:",@"cut:",@"select:",@"selectAll:",@"paste:"];
    if ([methodNameArr containsObject:NSStringFromSelector(action)]) {
        return YES;
    }
    return [super canPerformAction:action withSender:sender];
}
#pragma mark - 复制
- (void)copy:(id)sender {
    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setImage:self.img1.image];
}
- (void)paste:(id)sender {
    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
    self.img2.image = [pasteboard image];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self becomeFirstResponder];
    
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    [menuController setTargetRect:self.img1.frame inView:self];
    [menuController setMenuVisible:YES animated:YES];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    CopyView *copyView = [[CopyView alloc] initWithFrame:CGRectMake(20, 80, self.view.bounds.size.width - 40, 100)];
    [self.view addSubview:copyView];
}

注意

这时候显示出来的菜单名称是英文
如果要实现中文显示, 请参考(i18n) https://www.jianshu.com/p/cd072583856e

上一篇 下一篇

猜你喜欢

热点阅读