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