简单的实现苹果Assistive Touch。
自定义按钮:
//
// YFAssistiveButton.m
// 仿 Assistive Touch
//
// Created by dev on 16/6/21.
// Copyright © 2016年 SWALLE. All rights reserved.
//
#import "YFAssistiveButton.h"
@interface YFAssistiveButton()
{
CGPoint _beginPoint;
}
@end
@implementation YFAssistiveButton
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
_beginPoint = [touch locationInView:self];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touvh = [touches anyObject];
CGPoint currentPoint = [touvh locationInView:self];
CGFloat X = currentPoint.x - _beginPoint.x;
CGFloat Y = currentPoint.y - _beginPoint.y;
self.center = CGPointMake(self.center.x + X, self.center.y + Y);
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGFloat W = self.frame.size.width/2 ;
CGFloat H = self.frame.size.height/2;
CGFloat KScreenW = [UIScreen mainScreen].bounds.size.width;
CGFloat KScreenH = [UIScreen mainScreen].bounds.size.height;
CGFloat margenTop = self.center.y;
CGFloat margenBottom = KScreenH - self.center.y;
[UIView animateWithDuration:.2 animations:^{
if (margenTop < 160) {
self.center = CGPointMake(self.center.x + W, H);
return;
}else if (margenBottom < 160){
self.center = CGPointMake(self.center.x + W, KScreenH - H);
return;
}else{
if (self.center.x < KScreenW/2) {
self.center = CGPointMake(W, self.center.y);
return;
}else if (self.center.x > KScreenW/2){
self.center = CGPointMake(KScreenW - W, self.center.y);
return;
}
}
}];
}
@end
在控制器里面初始化自定义按钮
self.view.backgroundColor = [UIColor grayColor];
YFAssistiveButton *btn = [YFAssistiveButton buttonWithType:UIButtonTypeSystem];
_btn = btn;
btn.layer.cornerRadius = 5;
btn.frame = CGRectMake(5, 100, 50, 50);
[btn setBackgroundImage:[UIImage imageNamed:@"Assistive Touch"] forState:UIControlStateNormal];
[self.view addSubview:btn];