首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UILabel 實現長按選單複製功能:自訂類別與 UIMenuController 整合

     編輯:程式設計綜合問答

核心步驟

  1. 建立 UILabel 子類別(如 CopyableLabel)。
  2. 啟用使用者互動:self.userInteractionEnabled = YES;。
  3. 加入長按手勢辨識器:UILongPressGestureRecognizer。
  4. 實作 canBecomeFirstResponder 回傳 YES。
  5. 實作 canPerformAction:withSender: 僅回傳 copy: 為 YES。
  6. 實作 copy: 將 self.text 寫入 [UIPasteboard generalPasteboard]。
  7. 長按處理:[self becomeFirstResponder],顯示 UIMenuController。

完整實作 (CopyableLabel.m)

@implementation CopyableLabel

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) [self setup];
    return self;
}
- (void)awakeFromNib { [super awakeFromNib]; [self setup]; }

- (void)setup {
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [self addGestureRecognizer:lpgr];
}

- (BOOL)canBecomeFirstResponder { return YES; }

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    return action == @selector(copy:);
}

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

- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:self.bounds inView:self];
        [menu setMenuVisible:YES animated:YES];
    }
}

@end

使用方式

// Storyboard/XIB 中將 Label 類別設為 CopyableLabel
// 或程式碼建立
CopyableLabel *label = [[CopyableLabel alloc] initWithFrame:CGRectMake(20, 100, 280, 40)];
label.text = @"長按我可以複製";
[self.view addSubview:label];

延伸:支援選取、全選

需實作 UITextInput 協定或改用 UITextView(editable=NO, selectable=YES)以獲得完整選取體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved