上面列举的协议方法中有关联到其他许多iOS11中新增的类,后面会一一介绍。其实,完成了以上内容的了解,你就已经可以完全随心所欲的定制拖拽源组件了。
五、放置目的地
拖拽源是数据的提供者,放置目的地就是数据的接收者。前面我们也实验过,将自定义的拖拽源拖拽进UITextField后,文本框中会自动填充我们提供的文本数据。同样,对于任何自定义的UIView视图,我们也可以让其成为放置目的地,需要完成如下3步:
1.创建一个UIDropInteraction行为对象。
2.设置UIDropInteraction对象的代理并实现协议方法。
3.将其添加到自定义的视图中。
例如,我们将自定义的UILabel组件用来显示拖拽的文案:
//添加视图
- (void)viewDidLoad {
[super viewDidLoad];
//有关拖拽源的代码 前面已经列举过 这里不再重复
[self.view addSubview:self.dragView];
[self.view addSubview:self.dropLabel];
}
-(UILabel *)dropLabel{
if (!_dropLabel) {
_dropLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 300, 300, 30)];
_dropLabel.backgroundColor = [UIColor greenColor];
_dropLabel.userInteractionEnabled = YES;
[_dropLabel addInteraction:self.dropInteraction];
}
return _dropLabel;
}
//放置目的地行为对象
-(UIDropInteraction*)dropInteraction{
if (!_dropInteraction) {
_dropInteraction = [[UIDropInteraction alloc]initWithDelegate:self];
}
return _dropInteraction;
}
//这个方法返回是否响应此放置目的地的放置请求
-(BOOL)dropInteraction:(UIDropInteraction *)interaction canHandleSession:(id<UIDropSession>)session{
return YES;
}
//设置以何种方式响应拖放会话行为
-(UIDropProposal *)dropInteraction:(UIDropInteraction *)interaction sessionDidUpdate:(id<UIDropSession>)session{
return [[UIDropProposal alloc]initWithDropOperation:UIDropOperationCopy];
}
//已经应用拖放行为后执行的操作
-(void)dropInteraction:(UIDropInteraction *)interaction performDrop:(id<UIDropSession>)session{
[session loadObjectsOfClass:[NSString class] completion:^(NSArray<__kindof id<NSItemProviderReading>> * _Nonnull objects) {
self.dropLabel.text = objects.firstObject;
}];
}
上面的代码将我们自定义的拖拽源提供的Hello World拖放进了UILabel组件中。
六、关于UIDropInteraction类
与UIDragInteraction类类似,这个类的作用是让组件有相应放置操作的能力。其中属性如下:
//初始化方法
- (instancetype)initWithDelegate:(id<UIDropInteractionDelegate>)delegate;
//代理对象
@property (nonatomic, nullable, readonly, weak) id<UIDropInteractionDelegate> delegate;
//是否允许多个交互行为
@property (nonatomic, assign) BOOL allowsSimultaneousDropSessions;
七、UIDropInteractionDelegate协议
UIDropInteractionDelegate协议中所定义的方法全部是可选实现的,其用来处理用户放置交互行为。










