您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 富文本複製到剪貼簿的實作方式

編輯:iOS 相關資訊

在 iOS 中處理富文本複製時,常需要把 NSAttributedString 的純文字內容放入 UIPasteboard。以下以 DTCoreText 為背景,說明如何透過自訂 UIPasteboard 分類、長按手勢與 UIMenuController,完成「只複製文字、不包含圖片物件」的需求。

1. 為 UIPasteboard 增加富文本設定能力

可以先建立一個 UIPasteboard 的分類,讓剪貼簿支援設定 NSAttributedString。實作時,重點是取出 attributedString.string,並移除 Objective-C 中代表物件佔位符的字元,例如 ufffc,避免圖片或附件被一併複製。

NSString *plainText = attributedString.string;
plainText = [plainText stringByReplacingOccurrencesOfString:@"\ufffc" withString:@""];
NSMutableDictionary *item = [NSMutableDictionary dictionary];
[item setObject:plainText forKey:(NSString *)kUTTypeText];
self.items = @[item];

上述程式碼使用 MobileCoreServices 中的 kUTTypeText,表示剪貼簿內容為純文字。若需要更完整的富文本交換,也可以改用 RTF、HTML 或自訂 UTI,但此範例先以純文字為主。

2. 為視圖加入長按選單

若要讓使用者長按某個自訂視圖後出現「複製」選單,可加入 UILongPressGestureRecognizer,並在長按時呼叫 UIMenuController。記得將視圖設為第一回應者,否則選單不會顯示。

UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
gesture.minimumPressDuration = 1.0;
[self.selectedBackgroundView addGestureRecognizer:gesture];

長按回呼方法中,可先呼叫 becomeFirstResponder,再設定選單顯示位置:

UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setTargetRect:self.frame inView:self.superview];
[menu setMenuVisible:YES animated:YES];

3. 回應複製動作

自訂視圖需要覆寫 canBecomeFirstResponder 與 canPerformAction:withSender:,讓系統知道此視圖可以接收事件,而且只回應 copy: 方法。最後在 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:self.attributedText];
}

整體流程可以整理為:先定義剪貼簿寫入方式,再建立長按手勢,最後讓自訂視圖成為第一回應者並處理複製選單。這樣就能在富文本環境中,穩定地複製需要的文字內容。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved