UITextField禁止拖动粘贴 --UITextDragga

2020-07-02  本文已影响0人  WJ_月下

起始于一个需求,禁止文本输入框复制粘贴。自定义一个TextField,重写canPerFormAction方法:

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

直接全部禁用,完美收工。
直到某一天,测试过来一顿sao操作让我措不及防:
双击或者长按文字,进入了选中状态,再长按一会,文字就能拖动到其他文本框,实现了粘贴效果,嗯?
抢过测试机连上电脑,反复调试,canPerformAction无法拦截此sao操作,万能的千度也没找到灵感,无奈老老实实去看UITextField.h,找到了这个:

#if TARGET_OS_IOS

@interface UITextField () <UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting>
@end

#endif

直觉上UITextDraggable应该是目标。
点进去:

/* Defines a text draggable control.
 */
API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos)
@protocol UITextDraggable <UITextInput>

@property (nonatomic, weak, nullable) id<UITextDragDelegate> textDragDelegate;

定义文本拖动控制,就是这个了,看看UITextDragDelegate代理方法:

API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos)
@protocol UITextDragDelegate <NSObject>

@optional

/* Implement this to provide custom drag items when dragging out of a text control.
 * If you return an empty array here, no drag will occur.
 * The drag request provides the text range from which the user is dragging, and
 * a set of default drag items which would be used if this delegate method were
 * not implemented. You can modify and/or augment these at will.
 *
 * Note: this method might be called more than once. For instance, if the control
 * is asked to provide more items to add to an existing session.
 * You can detect this by checking the `existingItems` in the drag request.
 */
- (NSArray<UIDragItem *> *)textDraggableView:(UIView<UITextDraggable> *)textDraggableView itemsForDrag:(id<UITextDragRequest>)dragRequest;

很幸运,第一个就是寻找的方法,返回空数组就可以拦截拖动,那么解决方法有了,设置代理textDragDelegate,实现上面的代理方法,返回空数组:

- (NSArray<UIDragItem *> *)textDraggableView:(UIView<UITextDraggable> *)textDraggableView itemsForDrag:(id<UITextDragRequest>)dragRequest  API_AVAILABLE(ios(11.0)){
    return @[];
}
上一篇 下一篇

猜你喜欢

热点阅读