圆形View的点击区域

需求

任务进度的圆形区域可以点击(黄色圆圈内的部分都可以点击)

15300833198943.jpg

实现方法

实现思路

  1. 通过上图红色方框的UIView增加手势,如果仅仅是通过touchView.layer.cornerRadius的方式是无法将上图红色矩形的触摸区域变成黄色的圆形触摸区域。
  2. 通过hitTest:withEvent方法进行处理,判断圆圈范围,响应其触摸事件。若不在圆圈内,则不处理触摸事件。

代码


- (BOOL)touchPointInsideCircle:(CGPoint)center radius:(CGFloat)radius targetPoint:(CGPoint)point
{
    CGFloat dist = sqrtf((point.x - center.x) * (point.x - center.x) +
                         (point.y - center.y) * (point.y - center.y));
    return (dist <= radius);
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *hitView = nil;
    
    BOOL pointInRound = [self touchPointInsideCircle:self.touchView.center radius:163/2.0 targetPoint:point];
    if (pointInRound) {
        hitView = self.touchView;
    } else {
        hitView = self;
    }
    return hitView;
}

- (UIView *)touchView
{
    if (!_touchView) {
        _touchView = [[UIView alloc] init];
        _touchView.frame = CGRectMake(0, 0, 163, 163);
        _touchView.centerX = self.frame.size.width/2.0;
        _touchView.centerY = self.frame.size.height/2.0;
        _touchView.layer.cornerRadius = 163/2.0;
        _touchView.layer.masksToBounds = YES;
        _touchView.clipsToBounds = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touthVoid)];
        [_touchView addGestureRecognizer:tapGesture];
    }
    return _touchView;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 6,251评论 4 26
  • 好奇触摸事件是如何从屏幕转移到APP内的?困惑于Cell怎么突然不能点击了?纠结于如何实现这个奇葩响应需求?亦或是...
    Lotheve阅读 59,626评论 51 604
  • 触摸事件的生命周期 当我们手指触碰屏幕的那一刻,一个触摸事件便产生了。经过进程间通信,触摸事件被传递到合适的应用之...
    Gintok阅读 1,531评论 0 3
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,286评论 8 265
  • iOS开发中的事件处理 理论非原创,是对网上资料的整理以及Demo验证 一. UIResponder 1.1 事件...
    丧心病狂乐阅读 810评论 0 0

友情链接更多精彩内容