本文轉(zhuǎn)載自紅黑聯(lián)盟
#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為對象占位符,目的是當(dāng)富文本中有圖像時,只復(fù)制文本信息!!!
NSString *String = [[attributedString string] stringByReplacingOccurrencesOfString:@"\ufffc" withString:@""];
NSMutableDictionary *item = [NSMutableDictionary dictionaryWithCapacity:1];
[item setValue:htmlString forKey:(NSString *)kUTTypeText];
self.items = [NSArray arrayWithObject:item];
}
@end
給要復(fù)制的視圖添加長按事件:
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];}
重寫下面方法:
//是否截獲事件響應(yīng)
- (BOOL)canBecomeFirstResponder {
return YES;
}
//什么樣的操作會被響應(yīng)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return action == @selector(copy:);
}
- (void)copy:(id)sender {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setAttributedString:@"此處是富文本,其他同理"];
}