本文實例為大家分享了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上去;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答