Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField how to disable the paste? [duplicate]

UITextField how to disable the paste?

like image 904
isaced Avatar asked Apr 01 '13 14:04

isaced


1 Answers

overrides the canPerformAction:withSender: method to return NO for actions that you don't want to allow:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        if (action == @selector(paste:))
            return NO;
        if (action == @selector(select:))   
            return NO;   
        if (action == @selector(selectAll:))   
            return NO;  
        return [super canPerformAction:action withSender:sender];
    }

In Above Code you need to write only for paste

Another way

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (menuController) {
        [UIMenuController sharedMenuController].menuVisible = NO;
    }
    return NO;
}

Also check This link

EDITED

In iOS 7, you can do such like,,

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
    }];
    return [super canPerformAction:action withSender:sender];
}

For Swift User

override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(copy(_:)) || action == #selector(paste(_:)) {
        return false
    }

    return true
}

If you want to Open Date Picker or Picker view on TEXTFIELD click then below code work.

Add below two methods in your class.

//Hide Menu View
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

    if YOURTEXTFIELD.isFirstResponder {
        DispatchQueue.main.async(execute: {
            (sender as? UIMenuController)?.setMenuVisible(false, animated: false)
        })
        return false
    }

    return super.canPerformAction(action, withSender: sender)
}

//MUST Implement

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
            return false
}
like image 58
iPatel Avatar answered Oct 20 '22 01:10

iPatel