@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];
}
IOS 拖动事件和点击事件冲突
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1、当界面同时存在有定时器和UIScrollView时,比如:一个界面顶部是一个由定时器控制的无限轮播图,下面是一...
- 实现手势的代理方法中进行判断,这样就可以选择响应哪个事件 -(BOOL)gestureRecognizer:(UI...
- 最近开发遇到listView中解析爬虫回来的html数据超链接点击问题。有文字html标签链接和纯网址链接混合...