iOS开发Drag and Drop简介

1、Drag and Drop简介

  Drag and Drop是iOS11的新特性,可以将文本、图片进行拖拽到不同app中,实现数据的传递。只不过只能在iPad上使用,iPhone上只能app内部拖拽!

2、简单使用

  相关代码:

#import "ViewController.h"
#define CScreenWidth        [[UIScreen mainScreen] bounds].size.width
#define CScreenHeight       [[UIScreen mainScreen] bounds].size.height
#define ScreenHeight        self.view.frame.size.height
#define ScreenWidth         self.view.frame.size.width

@interface ViewController ()<UIDragInteractionDelegate,UIDropInteractionDelegate>

@property (nonatomic, strong)UIImageView *img;
@property (nonatomic, strong)UIImageView *img2;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.img =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic4"]];
    self.img.frame = CGRectMake(20, 40, CScreenWidth-40, 200);
    self.img.userInteractionEnabled = YES;
    [self.view addSubview:self.img];
    //Drag发送数据,Drop接收数据
    UIDragInteraction *dragInter = [[UIDragInteraction alloc] initWithDelegate:self];
    dragInter.enabled = YES;
    [self.img addInteraction:dragInter];
    [self.view addInteraction:[[UIDropInteraction alloc] initWithDelegate:self]];

    self.img2 =[[UIImageView alloc] init];
    self.img2.frame = CGRectMake(20, CScreenHeight-250, CScreenWidth-40, 200);
    self.img2.userInteractionEnabled = YES;
    [self.view addSubview:self.img2];

}
#pragma mark -UIDragInteractionDelegate
//提供数据源  开始拖拽
- (NSArray<UIDragItem *> *)dragInteraction:(UIDragInteraction *)interaction itemsForBeginningSession:(id<UIDragSession>)session{
    NSLog(@"11111----");
    self.img2.image = nil;
    NSItemProvider *item = [[NSItemProvider alloc] initWithObject:self.img.image];
    UIDragItem *dragItem = [[UIDragItem alloc] initWithItemProvider:item];
    dragItem.localObject = self.img.image;
    return @[dragItem];
}
//提供preview相关信息
- (nullable UITargetedDragPreview *)dragInteraction:(UIDragInteraction *)interaction previewForLiftingItem:(UIDragItem *)item session:(id<UIDragSession>)session{
    NSLog(@"22222----");
    UIDragPreviewParameters *parameters = [[UIDragPreviewParameters alloc] init];
    //设置蒙版mask
    parameters.visiblePath = [UIBezierPath bezierPathWithRoundedRect:self.img.bounds cornerRadius:20];
    //设置在哪个父视图和哪个位置展示
    UIDragPreviewTarget *target = [[UIDragPreviewTarget alloc] initWithContainer:self.img.superview center:self.img.center];
    UITargetedDragPreview *dragePreview = [[UITargetedDragPreview alloc] initWithView:interaction.view parameters:parameters target:target];
    return dragePreview;
}
//drag进行时
- (void)dragInteraction:(UIDragInteraction *)interaction willAnimateLiftWithAnimator:(id<UIDragAnimating>)animator session:(id<UIDragSession>)session{
    NSLog(@"33333----");
    [animator addCompletion:^(UIViewAnimatingPosition finalPosition) {
        if (finalPosition == UIViewAnimatingPositionEnd) {
            self.img.alpha = 0.5;
        }
    }];
}
//drag将要结束时调用
- (void)dragInteraction:(UIDragInteraction *)interaction session:(id<UIDragSession>)session willEndWithOperation:(UIDropOperation)operation{
    NSLog(@"44444----");
    [UIView animateWithDuration:0.5 animations:^{
        self.img.alpha = 1;
    }];
}
//drag动画将要取消时
- (void)dragInteraction:(UIDragInteraction *)interaction item:(UIDragItem *)item willAnimateCancelWithAnimator:(id<UIDragAnimating>)animator{
    NSLog(@"55555----");
    [animator addAnimations:^{
        self.img.alpha = .1;
    }];
}
//drag已经结束时调用
- (void)dragInteraction:(UIDragInteraction *)interaction session:(id<UIDragSession>)session didEndWithOperation:(UIDropOperation)operation{
    NSLog(@"66666----");
    [UIView animateWithDuration:0.5 animations:^{
        self.img.alpha = 1;
    }];
}

#pragma mark --UIDropInteractionDelegate
//是否可以接收来自Drag数据
- (BOOL)dropInteraction:(UIDropInteraction *)interaction canHandleSession:(id<UIDropSession>)session{
    if(session.localDragSession == nil){//说明数据来自外界
    }
    return [session canLoadObjectsOfClass:[UIImage class]];
}

//第二次判断是否可以接收 无法接收用UIDropOperationCancel
- (UIDropProposal *)dropInteraction:(UIDropInteraction *)interaction sessionDidUpdate:(id<UIDropSession>)session{
    UIDropOperation opera = session.localDragSession? UIDropOperationCopy:UIDropOperationCancel;
    return [[UIDropProposal alloc] initWithDropOperation:opera];
}

//取出来自drag的数据
- (void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session{
    if (session.localDragSession) {
      NSProgress *pregesss  = [session loadObjectsOfClass:[UIImage class]
                                               completion:^(NSArray<__kindof id<NSItemProviderReading>> * _Nonnull objects) {
                                                   // 回调的代码块默认就在主线程
                                                   for (id objc in objects) {
                                                       UIImage *image = (UIImage *)objc;
                                                       if (image) {
                                                           self.img2.image = image;
                                                       }
                                                   }
                                               }];
    }
}

@end

DragAndDrop.m文件

3、有关方法简介

  UIDragInteraction和Delegate方法:

@protocol UIDragInteractionDelegate, UIDragSession;
@class UIDragItem, UITargetedDragPreview;
API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos) @protocol UIDragAnimating <NSObject>
- (void)addAnimations:(void (^)(void))animations;
- (void)addCompletion:(void (^)(UIViewAnimatingPosition finalPosition))completion;
@end

UIKIT_EXTERN API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos) @interface UIDragInteraction : NSObject <UIInteraction>
- (instancetype)initWithDelegate:(id<UIDragInteractionDelegate>)delegate NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@property (nonatomic, nullable, readonly, weak) id<UIDragInteractionDelegate> delegate;
@property (nonatomic) BOOL allowsSimultaneousRecognitionDuringLift;
@property (nonatomic, getter=isEnabled) BOOL enabled;
@property (class, nonatomic, readonly, getter=isEnabledByDefault) BOOL enabledByDefault;
@end

API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos) @protocol UIDragInteractionDelegate <NSObject>
@required
//提供数据源  长按UI开始拖拽
- (NSArray<UIDragItem *> *)dragInteraction:(UIDragInteraction *)interaction itemsForBeginningSession:(id<UIDragSession>)session;
@optional
//提供UITargetedDragPreview的相关信息  长按UI是有个lift(UI举起效果,系统自动生成)
//返回nil 没有效果;   不实现该方法 interaction.view自动生成UITargetedDragPreview
- (nullable UITargetedDragPreview *)dragInteraction:(UIDragInteraction *)interaction previewForLiftingItem:(UIDragItem *)item session:(id<UIDragSession>)session;
//drag发生时调用
- (void)dragInteraction:(UIDragInteraction *)interaction willAnimateLiftWithAnimator:(id<UIDragAnimating>)animator session:(id<UIDragSession>)session;
//将要开始drag
- (void)dragInteraction:(UIDragInteraction *)interaction sessionWillBegin:(id<UIDragSession>)session;
//是否允许数据移动 app内移动有效,跨app总是复制数据
- (BOOL)dragInteraction:(UIDragInteraction *)interaction sessionAllowsMoveOperation:(id<UIDragSession>)session;
//是否允许跨应用程序进行drag ipad
- (BOOL)dragInteraction:(UIDragInteraction *)interaction sessionIsRestrictedToDraggingApplication:(id<UIDragSession>)session;
//设置预览视图是否显示原始大小
- (BOOL)dragInteraction:(UIDragInteraction *)interaction prefersFullSizePreviewsForSession:(id<UIDragSession>)session;
//已经结束移动
- (void)dragInteraction:(UIDragInteraction *)interaction sessionDidMove:(id<UIDragSession>)session;
//drag将要结束时调用
- (void)dragInteraction:(UIDragInteraction *)interaction session:(id<UIDragSession>)session willEndWithOperation:(UIDropOperation)operation;
//drag已经结束时调用
- (void)dragInteraction:(UIDragInteraction *)interaction session:(id<UIDragSession>)session didEndWithOperation:(UIDropOperation)operation;
//拖拽源进行了放置操作后调用
- (void)dragInteraction:(UIDragInteraction *)interaction sessionDidTransferItems:(id<UIDragSession>)session;
//设置是否允许向拖拽中的项目添加数据 返回数据载体数组 drag时点击拖拽的组件调用
- (NSArray<UIDragItem *> *)dragInteraction:(UIDragInteraction *)interaction itemsForAddingToSession:(id<UIDragSession>)session withTouchAtPoint:(CGPoint)point;
//设置允许进行拖拽中追加数据的拖拽行为会话
- (nullable id<UIDragSession>)dragInteraction:(UIDragInteraction *)interaction sessionForAddingItems:(NSArray<id<UIDragSession>> *)sessions withTouchAtPoint:(CGPoint)point;
//将要向拖拽组件中追加数据时调用
- (void)dragInteraction:(UIDragInteraction *)interaction session:(id<UIDragSession>)session willAddItems:(NSArray<UIDragItem *> *)items forInteraction:(UIDragInteraction *)addingInteraction;
//设置拖拽动作取消的视图动画 返回nil则消除动画
- (nullable UITargetedDragPreview *)dragInteraction:(UIDragInteraction *)interaction previewForCancellingItem:(UIDragItem *)item withDefault:(UITargetedDragPreview *)defaultPreview;
//drag动画将要取消时调用
- (void)dragInteraction:(UIDragInteraction *)interaction item:(UIDragItem *)item willAnimateCancelWithAnimator:(id<UIDragAnimating>)animator;

  UIDropInteraction和Delegate方法:

@protocol UIDragAnimating, UIDropInteractionDelegate, UIDropSession;
@class UIDragItem, UITargetedDragPreview;

UIKIT_EXTERN API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos) @interface UIDropInteraction : NSObject <UIInteraction>

- (instancetype)initWithDelegate:(id<UIDropInteractionDelegate>)delegate NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

@property (nonatomic, nullable, readonly, weak) id<UIDropInteractionDelegate> delegate;
@property (nonatomic, assign) BOOL allowsSimultaneousDropSessions;
@end
typedef NS_ENUM(NSUInteger, UIDropOperation) {
    UIDropOperationCancel   = 0,
    UIDropOperationForbidden = 1,
    UIDropOperationCopy      = 2,
    UIDropOperationMove      = 3,
} API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos);

UIKIT_EXTERN API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos) @interface UIDropProposal : NSObject <NSCopying>
- (instancetype)initWithDropOperation:(UIDropOperation)operation NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@property (nonatomic, readonly) UIDropOperation operation;
@property (nonatomic, getter=isPrecise) BOOL precise;
@property (nonatomic) BOOL prefersFullSizePreview;
@end

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

@optional
//是否可以处理来自Drag的数据
- (BOOL)dropInteraction:(UIDropInteraction *)interaction canHandleSession:(id<UIDropSession>)session;
//Drag的UI元素进入Drop的区域
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidEnter:(id<UIDropSession>)session;
//第二次判断是否可以接收 无法接收用UIDropOperationCancel
- (UIDropProposal *)dropInteraction:(UIDropInteraction *)interaction sessionDidUpdate:(id<UIDropSession>)session;
//Drag的UI元素离开Drop的区域
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidExit:(id<UIDropSession>)session;
//取出来自drag的数据
- (void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session;
//drop结束
- (void)dropInteraction:(UIDropInteraction *)interaction concludeDrop:(id<UIDropSession>)session;
//整个Drag和Drop结束
- (void)dropInteraction:(UIDropInteraction *)interaction sessionDidEnd:(id<UIDropSession>)session;
//手指松开,控制Drag Preview 如何自然的过渡到Drop之后的Preview
- (nullable UITargetedDragPreview *)dropInteraction:(UIDropInteraction *)interaction previewForDroppingItem:(UIDragItem *)item withDefault:(UITargetedDragPreview *)defaultPreview;
//手指松开Drop时,控制Drop区域的其他UI元素如何展示动画
- (void)dropInteraction:(UIDropInteraction *)interaction item:(UIDragItem *)item willAnimateDropWithAnimator:(id<UIDragAnimating>)animator;
@end

原文地址:https://www.cnblogs.com/xianfeng-zhang/p/8951805.html

时间: 2024-10-15 01:53:30

iOS开发Drag and Drop简介的相关文章

iOS开发UI篇—CAlayer简介

iOS开发UI篇—CALayer简介 一.简单介绍 在iOS中,你能看得见摸得着的东西基本上都是UIView,比如一个按钮.一个文本标签.一个文本输入框.一个图标等等,这些都是UIView. 其实UIView之所以能显示在屏幕上,完全是因为它内部的一个图层,在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层 @property(nonatomic,readonly,retain) CALayer *layer; 当

iOS开发多线程篇—多线程简介

iOS开发多线程篇-多线程简介 一.进程和线程 1.什么是进程 进程是指在系统中正在执行的一个应用程序 每一个进程之间是独立的.每一个进程均执行在其专用且受保护的内存空间内 比方同一时候打开QQ.Xcode,系统就会分别启动2个进程 通过"活动监视器"能够查看Mac系统中所开启的进程 2.什么是线程 1个进程要想运行任务,必须得有线程(每1个进程至少要有1条线程) 线程是进程的基本运行单元,一个进程(程序)的全部任务都在线程中运行 比方使用酷狗播放音乐.使用迅雷下载电影,都须要在线程中

iOS开发UITouch触摸API简介

1.UITouch简介 当用户触摸屏幕时,会创建一个UITouch对象: UITouch的作用保存着触摸相关的信息,比如触摸的位置.时间.阶段等: 当从开始到结束,系统会更新UITouch对象,结束时会被销毁. 期间所有的UITouch对象都被包含在UIEvent事件对象中,由管理程序UIApplication对象将事件分发. 2.触摸事件调用方法 //响应触摸事件 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(null

iOS开发UI篇—UIView简介

一.情况一,设置阴影 // shadowColor 阴影颜色 self.view.layer.shadowColor = UIColorFromRGB(0x000000).CGColor; // shadowOffset 偏移位置 self.view.layer.shadowOffset = CGSizeMake(2, 4); // 透明度 0 到1之间 self.view.layer.shadowOpacity = 0.5; // 阴影圆角 self.view.layer.shadowRadi

文顶顶iOS开发博客链接整理及部分项目源代码下载

文顶顶iOS开发博客链接整理及部分项目源代码下载 网上的iOS开发的教程很多,但是像cnblogs博主文顶顶的博客这样内容图文并茂,代码齐全,示例经典,原理也有阐述,覆盖面宽广,自成系统的系列教程却很难找.如果你是初学者,在学习了斯坦福iOS7公开课和跟着文顶顶的博客做项目之后,最快只需要2个月时间,就基本可以独立完成iOS App的开发工作.有经验的开发者也可以在该博客中寻找代码片段进行学习借鉴,必有所收获. 在此也向@文顶顶 表示严重感谢! 由于文顶顶博客博文繁多,每次找文章需要频繁的翻页,

React Native的iOS开发步骤以及崩溃收集

React Native的iOS开发以及崩溃收集 简介 React Native使你能够在Javascript和React的基础上获得完全一致的开发体验,构建世界一流的原生APP. React Native着力于提高多平台开发的开发效率 -- 仅需学习一次,编写任何平台.(Learn once, write anywhere) Facebook已经在多项产品中使用了React Native,并且将持续地投入建设React Native. 准备 安装 iOS只能MAC下开发,需要Xcode; An

IOS开发——使用数据库

IOS开发——使用FMDB数据库 简介 需求作用: 如果需要保存大量的结构较为复杂的数据的时候,使用数据库,例如交规考试项目 1.数据库的基本介绍 数据库(DB)是一种数据模型组织起来并存放存储管理的数据仓库.它是由文件管理发展起来的,如今的数据库基本上都是关系型数据库. 数据库的基本操作是增.删.查.改. 常见的几种数据库,Oracle,Access,SQL Server,DB2,Mysql 手机上使用的数据库为SQLite,因为它占用资源很好,易于配置等原因. 2.mesaSQLite 使用

iOS开发 数据库FMDB

iOS开发  数据库FMDB 1.简介 需求作用: 如果需要保存大量的结构较为复杂的数据时候, 使用数据库, 例如交规考试项目 常用的数据库: (1)Microsoft SQL Server 2000/2008, 中小企业使用较多 (2)Oracle 比较复杂, 大企业使用较多 (3)Mysql数据库, 网站使用较多 (4)sqlite: 本地数据库, 访问数据足够快, 直接访问文件 足够简单, 功能相对其他数据库软件不是特别齐全, 足够用了  足够小, 系统不超过1M, 适合在移动端上使用 2

iOS开发项目篇—16OAuth授权简介

iOS开发项目篇—16OAuth授权简介 一.资源的授权 在互联网行业,公司要能长期存活下来,用户量很重要,比如腾讯.新浪,它们的用户量是非常巨大的 要想长期留住用户,用户资源(数据)的管理也很重要,如果你经常在不经过用户同意的情况下,把用户的一些资源共享出去,那肯定是留不住用户的,甚至会遭到法律的制裁 但是,有时候确实要把某些用户资源共享出去,比如第三方想访问用户的QQ数据.第三方想访问用户的新浪微博数据 要想把用户资源共享出去,就必须取得用户的同意,那么这里就有个资源授权的问题 资源授权的方