IOS开发之文本复制

本文转载自红黑联盟

#import   
#import //添加此框架   
@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:@"此处是富文本,其他同理"]; 
} 

你可能感兴趣的:(IOS开发之文本复制)