IOS realizes the floating effect of dragging view with fingers


This example shares the specific code of dragging view to float with your finger in IOS for your reference. The specific contents are as follows

design sketch:

1. Customize the view to float with the finger

// OrangeView.m
//Drag the view to float with your finger
// Created by llkj on 2017/8/16.
// Copyright  ©  2017 laynecheung. All rights reserved

#import "OrangeView.h"

@implementation OrangeView

//Called when you start touching the screen
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

 NSLog(@"%s", __func__);

//Called when starting to move when touching (called continuously when moving)
//Nsset: unordered
//Nsarray: ordered
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

 NSLog(@"%s", __func__);

 UITouch *touch = [touches anyObject];

 //Find the offset = x of the current point of the finger - X of the previous point of the finger
 CGPoint currentPoint = [touch locationInView:self];
 CGPoint prePoint = [touch previousLocationInView:self];

 NSLog(@"ccurrentPoint = %@", NSStringFromCGPoint(currentPoint));
 NSLog(@"prePiont = %@", NSStringFromCGPoint(prePoint));

 CGFloat offSetX = currentPoint.x - prePoint.x;
 CGFloat offSetY = currentPoint.y - prePoint.y;

 self.transform = CGAffineTransformTranslate(self.transform, offSetX, offSetY);

//Called when the finger leaves the screen
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

 NSLog(@"%s", __func__);

//This method is called when a system event occurs (call in, automatic shutdown)
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

 NSLog(@"%s", __func__);

2. Create a custom view

Drag a view in the storyboard to bind its class to orangeview;
Or manually add the code creation to the view of the controller;

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.