原始地址:IOS開發之文本複製
本文基於富文本:DTCoreText
#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 *htmlString = [[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:@"此處是富文本,其他同理"];}