@interface YQBAddHomeWorkBtn()<UIGestureRecognizerDelegate>
@end
@implementation YQBAddHomeWorkBtn
{
CGPoint originalLocation; //全局变量 用于存储起始位置
BOOL shouldPassEvent; // 是否需要传递事件
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.userInteractionEnabled = YES;
// 取消高亮
[self setAdjustsImageWhenHighlighted:NO];
[self setNeedsUpdateConstraints];
}
return self;
}
- (instancetype)init
{
if (self = [super init]) {
self.userInteractionEnabled = YES;
// 取消高亮
[self setAdjustsImageWhenHighlighted:NO];
[self setNeedsUpdateConstraints];
}
return self;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
originalLocation = [touch locationInView:self];
shouldPassEvent = YES;
[[self superview] bringSubviewToFront:self];
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
//计算位移=当前位置-起始位置
CGPoint point = [[touches anyObject] locationInView:self];
float dx = point.x - originalLocation.x;
float dy = point.y - originalLocation.y;
//计算移动后的view中心点
CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
/* 限制用户不可将视图拖出屏幕 */
float halfx = CGRectGetMidX(self.bounds);
//x坐标左边界
newcenter.x = MAX(halfx + offset, newcenter.x);
//x坐标右边界
newcenter.x = MIN(self.superview.bounds.size.width - halfx - offset, newcenter.x);
//y坐标同理
float halfy = CGRectGetMidY(self.bounds);
// y坐标上边界
newcenter.y = MAX(halfy + 80, newcenter.y);
newcenter.y = MIN(self.superview.bounds.size.height - halfy - offset, newcenter.y);
// 判断是否需要传递事件
shouldPassEvent = CGPointEqualToPoint(newcenter, originalLocation);
//移动view
self.center = newcenter;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (shouldPassEvent) {//点击事件 需要传递点击
[super touchesEnded:touches withEvent:event];
}
}
- (void)updateConstraints
{
[self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self);
}];
[super updateConstraints];
}
网友评论