本文基於富文本庫 DTCoreText,記錄如何把富文本內容復制到系統剪貼板,並通過長按菜單觸發。
系統的 UIPasteboard 默認並沒有直接接受 NSAttributedString 的接口,需要通過分類擴展一個 setter。頭文件:
#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
這裡有兩個細節值得注意。一是 \ufffc 這個字符:它是 Objective-C 中表示「object replacement character」的佔位符,NSAttributedString 裡每嵌入一張圖片(NSTextAttachment)就會佔一個這樣的位置。把佔位符替換成空字符串,就能只提取純文字,避免剪貼板裡出現亂碼方塊。二是 kUTTypeText 這個 UTI 類型標識,它決定粘貼方能識別這份剪貼板數據的格式——因此必須引入 MobileCoreServices 框架。
UILongPressGestureRecognizer *gestureRecognizer =
[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
[self.selectedBackgroundView addGestureRecognizer:gestureRecognizer];
gestureRecognizer.minimumPressDuration = 1.0;
手勢回調中,先讓自己成為第一響應者(first responder),再彈出系統的 UIMenuController:
- (void)longTap:(UILongPressGestureRecognizer *)ges
{
[self becomeFirstResponder];
UIMenuController *menu = [UIMenuController sharedMenuController];
// 設置菜單出現的位置
[menu setTargetRect:[self frame] inView:self.superview];
[menu setMenuVisible:YES animated:YES];
}
順序很重要:必須先 becomeFirstResponder,菜單才會顯示。UIMenuController 是沿著響應者鏈向上尋找能處理 copy: 的對象,如果當前視圖不是第一響應者,菜單根本不會出現。
// 是否接收成為第一響應者
- (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:@"此處是富文本,其他同理"];
}
這三個方法缺一不可:
· canBecomeFirstResponder 返回 YES,否則 becomeFirstResponder 會失敗,菜單彈不出來。
· canPerformAction:withSender: 決定菜單裡出現哪些按鈕。只返回 @selector(copy:),菜單上就僅有「拷貝」;如果还想支持粘貼、剪切、刪除,在這裡並上對應的 selector 即可。
· copy: 是實際執行復制的入口,把數據寫入 UIPasteboard 就完成。
還有一點容易遺漏:視圖若被子視圖覆蓋或所在的 window 不是 keyWindow,成為第一響應者也可能失敗。遇到菜單不彈的情況,先檢查這兩處。