iOS 区域响应交互

  • 在一个正方形的按钮中只有圆形区域可以响应
//  获取响应的视图
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
// 获取响应位置
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
  • CustomButton 类
#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end
#import "CustomButton.h"

@implementation CustomButton


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.userInteractionEnabled || [self isHidden] || self.alpha <= 0.01) { // 如果是禁止交互,隐藏,透明则不用响应 返回 nil
        return nil;
    }
    
    if ([self pointInside:point withEvent:event]) {
        //遍历当前对象的子视图
        __block UIView *hit = nil;
        [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 坐标转换
            CGPoint vonvertPoint = [self convertPoint:point toView:obj];
            //调用子视图的hittest方法
            hit = [obj hitTest:vonvertPoint withEvent:event];
            // 如果找到了接受事件的对象,则停止遍历
            if (hit) {
                *stop = YES;
            }
        }];
        
        if (hit) {
            return hit;
        }
        else{
            return self;
        }
    }
    else{
        return nil;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGFloat x1 = point.x;
    CGFloat y1 = point.y;
    
    CGFloat x2 = self.frame.size.width / 2;
    CGFloat y2 = self.frame.size.height / 2;
    
    double dis = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    // 67.923
    if (dis <= self.frame.size.width / 2) {
        return YES;
    }
    else{
        return NO;
    }
}
CustomButton *customButton = [[CustomButton alloc] initWithFrame:CGRectMake(100, 100, 120, 120)];
    customButton.backgroundColor = [UIColor blueColor];
    [customButton addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:customButton];
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 11,322评论 4 26
  • 这是一本武林秘籍,教你如何读书,如何学习,教你方法不是只教你努力。更不是鸡汤。 其中我最喜欢的:吞青蛙,每天第...
    六界神话阅读 1,855评论 0 0
  • (连载)《美梦如璇·第六章·第四十四节》 又到了夏季,多雨的夏季。 不时出现的闪电、闷雷和积雨。 想着那天,你伸出...
    叶子程阅读 1,571评论 1 1
  • 这两天给自己一个挑战,每天上下班步行,大概需要1小时20分钟左右,我的健康没有完成,每天要走3万步,加油完成。今天...
    江宏祥阅读 1,166评论 0 0

友情链接更多精彩内容