Enable copy and paste on UITextField without making it editable

后端 未结 6 2001
孤街浪徒
孤街浪徒 2020-11-27 17:54

I want the text in a UITextField (or ideally, a UILabel) to be non-editable, but at the same time give the user the ability to cop

6条回答
  •  余生分开走
    2020-11-27 18:07

    This question is pretty old and I'm surprised nobody has posted a solution without subclassing. The idea presented in @mrueg's answer is correct, but you shouldn't need to subclass anything. I just came across this problem and solved it like this:

    In my view controller:

    - (void)viewDidLoad {
        self.textField.delegate = self;
        self.textField.text = @"Copyable, non-editable string.";
    }
    
    - (BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    - (void)copyTextFieldContent:(id)sender {
        UIPasteboard* pb = [UIPasteboard generalPasteboard];
        pb.string = self.textField.text;
    }
    
    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
        // UIKit changes the first responder after this method, so we need to show the copy menu after this method returns.
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [self becomeFirstResponder];
             UIMenuController* menuController = [UIMenuController sharedMenuController];
             UIMenuItem* copyItem = [[UIMenuItem alloc] initWithTitle:@"Copy"
                                                               action:@selector(copyTextFieldContent:)];
             menuController.menuItems = @[copyItem];
             CGRect selectionRect = textField.frame;
             [menuController setTargetRect:selectionRect inView:self.view];
             [menuController setMenuVisible:YES animated:YES];
         });
         return NO;
    }
    

    If you want to make this work for a UILabel, it should work the same way with just adding a tap gesture recognizer instead of using the delegate method.

提交回复
热议问题