仿iPhone-AssistiveTouch

拖拽效果.gif

UIView的触摸事件主要有:文字来源
一根或者多根⼿手指开始触摸view,系统会⾃自动调⽤用view的下⾯面⽅方法.

  • (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    一根或者多根⼿手指在view上移动时,系统会⾃自动调⽤用view的下⾯面⽅方法 (随着⼿手指的移动,会持续调⽤用该⽅方法,也就是说这个⽅方法会调⽤用很多次)
  • (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    一根或者多根⼿手指离开view,系统会⾃自动调⽤用view的下⾯面⽅方法
  • (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    一当突然发生系统事件的时候,例如突然来了系统电话,或是手机没电的时候,系统就会自动调用
  • (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

代码事例(被抛弃的小功能)

// .h文件
#import 

@interface MXDragEnableView : UIImageView

@end

// .m文件
#import "MXDragEnableView.h"
#define PADDING     5

@interface MXDragEnableView () {
    CGPoint beginPoint;
}

@end
@implementation MXDragEnableView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    beginPoint = [touch locationInView:self];
    [[self superview] bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint nowPoint = [touch locationInView:self];
    float offsetX = nowPoint.x - beginPoint.x;
    float offsetY = nowPoint.y - beginPoint.y;
    self.center = CGPointMake(self.center.x + offsetX, self.center.y + offsetY);
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self setNewDraggedViewFrame];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self setNewDraggedViewFrame];
}

- (void)setNewDraggedViewFrame
{
    float marginLeft = self.frame.origin.x;
    float marginRight = self.superview.frame.size.width - self.frame.origin.x - self.frame.size.width;
    float marginTop = self.frame.origin.y;
    float marginBottom = self.superview.frame.size.height - self.frame.origin.y - self.frame.size.height;
    
    //    marginLeft

你可能感兴趣的:(仿iPhone-AssistiveTouch)