iOS實現拖拽View跟隨手指浮動效果
阿新 • • 發佈:2020-02-22
本文例項為大家分享了iOS實現拖拽View跟隨手指浮動的具體程式碼,供大家參考,具體內容如下
效果圖:
1.自定義要跟隨手指浮動的那個View
// // OrangeView.m // 拖拽View跟隨手指浮動 // // Created by llkj on 2017/8/16. // Copyright © 2017年 LayneCheung. All rights reserved. // #import "OrangeView.h" @implementation OrangeView //當開始觸控式螢幕幕的時候呼叫 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } //觸控時開始移動時呼叫(移動時會持續呼叫) //NSSet:無序 //NSArray:有序 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); UITouch *touch = [touches anyObject]; //求偏移量 = 手指當前點的X - 手指上一個點的X 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); } //當手指離開螢幕時呼叫 -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } //當發生系統事件時就會呼叫該方法(電話打入,自動關機) - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ NSLog(@"%s",__func__); } @end
2.建立自定義的View
在storyboard中拖一個View繫結他的類為OrangeView;
或者程式碼建立手動新增到控制器的View上去;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。