IOS开发之文本复制

本文转载自红黑联盟

#import <Foundation/Foundation.h>  
#import <MobileCoreServices/UTCoreTypes.h>//添加此框架   
@interface UIPasteboard (AttributedString) 
- (void) setAttributedString:(NSAttributedString *)attributedString;
@end 
#import "UIPasteboard+AttributedString.h"
@implementation UIPasteboard (AttributedString) 
- (void) setAttributedString:(NSAttributedString *)attributedString {     //\ufffc为对象占位符,目的是当富文本中有图像时,只复制文本信息!!!
      NSString *String = [[attributedString string] stringByReplacingOccurrencesOfString:@"\ufffc" withString:@""];
      NSMutableDictionary *item = [NSMutableDictionary dictionaryWithCapacity:1]; 
     [item setValue:htmlString forKey:(NSString *)kUTTypeText];
      self.items = [NSArray arrayWithObject:item]; 
}
@end 

给要复制的视图添加长按事件:

UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
[self.selectedBackgroundView addGestureRecognizer:gestureRecognizer];  
gestureRecognizer.minimumPressDuration = 1.0;
- (void)longTap:(UILongPressGestureRecognizer *)ges{ [self becomeFirstResponder]; 
UIMenuController * menu = [UIMenuController sharedMenuController];        //尺寸和添加到哪里 
[menu setTargetRect: [self frame] inView: self.superView]; 
[menu setMenuVisible: YES animated: YES];}

重写下面方法:

//是否截获事件响应 
 - (BOOL)canBecomeFirstResponder {
     return YES; 
} 
//什么样的操作会被响应  
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
     return action == @selector(copy:); 
}
- (void)copy:(id)sender {
     UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
     [pasteboard setAttributedString:@"此处是富文本,其他同理"]; 
} 

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,247评论 25 709
  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 11,316评论 4 26
  • 好奇触摸事件是如何从屏幕转移到APP内的?困惑于Cell怎么突然不能点击了?纠结于如何实现这个奇葩响应需求?亦或是...
    Lotheve阅读 59,032评论 51 604
  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 9,367评论 1 22
  • 毕业一年多,做过一份工作,时长1年零三个月。 结束上一份工作到现在再次找到工作间隔5个月。 当初辞职后就一直忙着找...
    44e387f08401阅读 2,586评论 0 0

友情链接更多精彩内容