UILabel實現(xiàn)長按復制功能

1. 創(chuàng)建 UILabel 的子類

@interface YYCopyLabel : UILabel

@property (nonatomic, assign) BOOL copyEnabled;

@end

2. 增加 UILongPressGestureRecognizer 手勢

- (void)setCopyEnabled:(BOOL)copyEnabled
{
    _copyEnabled = copyEnabled;
    
    // 確保 UILabel 可交互
    self.userInteractionEnabled = copyEnabled;
    
    if (copyEnabled && !self.longPressGR) {
        self.longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                         action:@selector(handleLongPressGesture:)];
        [self addGestureRecognizer:self.longPressGR];
    }
    
    if (self.longPressGR) {
        self.longPressGR.enabled = copyEnabled;
    }
}

- (void)handleLongPressGesture:(UILongPressGestureRecognizer *)longPressGR
{
    if (longPressGR.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    }
}

3. 實現(xiàn) UIMenuController 的相關協(xié)議

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    // 自定義響應UIMenuItem Action,例如你可以過濾掉多余的系統(tǒng)自帶功能(剪切,選擇等),只保留復制功能。
    return (action == @selector(copy:));
}

- (void)copy:(id)sender
{
    [[UIPasteboard generalPasteboard] setString:self.text];
}

4. 使用UIMenuController出現(xiàn)UIViewControllerHierarchyInconsistency crash

  • Exception log: UICompatibilityInputViewController的父控制器必須是UIInputWindowController,不能是其他自定義的控制器。
'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<UICompatibilityInputViewController: 0x7f9b37f00fa0> should have parent view controller:<ClipboardLabelViewController: 0x7f9b3b009b90> but requested parent is:<UIInputWindowController: 0x7f9b3801d400>'
  • 崩潰原因:調用UIMenuController控制器的視圖層級樹(view tree)存在命名為inputView的view。上面例子是因為ClipboardLabelViewController 定義了inputView。
@property (nonatomic, strong) UIView *inputView;
  • 解決辦法:找出自定義inputView,修改其命名,例如你可以改成myInputView

5. YYCopyLabelDemo

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 標簽(空格分隔): IOS 在iOS8 之后, 我們發(fā)現(xiàn)UILabel不在為我們提供長按彈出復制等操作了, 我們來...
    袁俊亮技術博客閱讀 1,840評論 0 0
  • 務實中尋求那么一點點的小浪漫
    寧靜致遠_3962閱讀 78評論 0 0
  • 終于到了除夕的晚上,馬上開始我已經(jīng)期待了很久的重頭戲。到了晚上的時候八點多時,鄉(xiāng)下的天已經(jīng)黑盡了,我和哥哥來到...
    637ea2df2016閱讀 473評論 0 2
  • 幸存者36季網(wǎng)上評分并不太高,不過目前來看似乎沒有網(wǎng)上說的那么差勁,只不過確實是有些人過于自大,策略也不太好,以至...
    一木一心閱讀 482評論 0 1
  • 好幾日沒在手機上寫東西,只在特定的本子仍記錄著每日的歷程。 兩年的駐村已經(jīng)結束,心中的感覺是復雜糾結的:雖經(jīng)歷駐村...
    卡斯特羅梁閱讀 460評論 0 4

友情鏈接更多精彩內容