IOS开发之文本复制

来源:互联网 发布:高中语文知乎 编辑:程序博客网 时间:2024/05/14 19:07

原始地址: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:@"此处是富文本,其他同理"];}


原创粉丝点击