文本段的整体复制

在做项目的时候经常遇到一些地方需要复制文本框的内容,虽然简单但还是稍做总结。

对复制的操作一般是在标签栏上(Label),响应一般是长按手势(LongPressGesture),其他情况不做赘述。

首先声明一个方法:

- (void)copyActionWithView:(UIView *)view WithString:(NSString *)text WithSuperView:(UIView *)superView;
在标签栏上添加手势,设置可触摸属性:

_contentLabel.userInteractionEnabled = YES;
UILongPressGestureRecognizer * longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[_contentLabel addGestureRecognizer:longPressGR];

- (void)longPress:(UILongPressGestureRecognizer *)sender{
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self copyActionWithView:sender.view WithString:self.contentLabel.text WithSuperView:nil];
    }
}

实现:(一般在控制器上)

- (void)copyActionWithView:(UIView *)view WithString:(NSString *)text WithSuperView:(UIView *)superView{
    [self becomeFirstResponder];
    self.ownCopyString = text;
    UIMenuController *menu = [UIMenuController sharedMenuController];
    UIMenuItem * copy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyAction:)];
    menu.menuItems = [NSArray arrayWithObjects: copy, nil];
    CGRect targetRect;
    if (superView) {
        CGRect beginRcet = [view convertRect:view.frame toView:superView];
        CGRect minRect = [superView convertRect:superView.frame toView:superView.superview];
        CGRect endRect = [superView.superview convertRect:superView.superview.frame toView:self.view];
        targetRect.origin.y = endRect.origin.y + minRect.origin.y / 2.0 + beginRcet.origin.y / 2.0 + 8;
    }else{
        targetRect = [view convertRect:view.frame toView:self.view];
        targetRect.origin.y -= 20;
    }
    targetRect.origin.x = 110;
    targetRect.size.width = 100;
    targetRect.size.height = 17.1;
    [menu setTargetRect:targetRect inView:self.view];
    [menu setMenuVisible:YES animated:YES];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(copyAction:)) {
        return YES;//显示
    }
    return NO;//不显示
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (void)copyAction:(id)sender{
    UIPasteboard * pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:self.ownCopyString];
}

在通常情况下,需要复制的文本都是在较深层次的视图,一般要通过协议实现具体的方法,这里只是简要说明。另外还可以自定义弹出点(复制小窗口)的位置。

上传一个示例,展示一下效果:







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值