如何在 iOS 应用中与 UIButton 的特定区域进行交互

Posted

技术标签:

【中文标题】如何在 iOS 应用中与 UIButton 的特定区域进行交互【英文标题】:How to interact with specific area of UIButton in iOS app 【发布时间】:2013-11-06 08:02:42 【问题描述】:

我必须在点击按钮的特定区域时执行操作。实际上在只有粉红色可见的区域。不在那个区域之外。请查看随附的图片以及此消息,如果我有任何不清楚的地方,请告诉我。

【问题讨论】:

整个按钮都是粉红色的。你说的是哪个粉红色区域? 我认为这是关于分析图像像素的,大多数人都没有理解它...... 【参考方案1】:

您需要创建自定义 UIButton 类并添加方法:

-(BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event

    if(![super pointInside:point withEvent:event]) return NO;

    return [bezierPath containsPoint:point];

bazierPath 可见区域你的按钮。看这个链接docs

【讨论】:

【参考方案2】:

您可以添加自定义选择器,然后在那里获得接触点。然后检查该点是否在您的特定区域内。

[pinkButton addTarget:self action:@selector(buttonTouched:withEvent:) forControlEvents: UIControlEventTouchDown];
//Define the area here or get the exact frame if it is already a UIView
CGRect frameOfSpecificArea = CGRectMake(10, 20, 30, 40);
- (void)buttonTouched:(UIButton *)sender withEvent:event 
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint tapPoint = [touch locationInView:sender];
    NSLog(@"Pink Button touched x : %f y : %f", tapPoint.x, tapPoint.y);
    BOOL pointIsInside = CGRectContainsPoint(frameOfSpecificArea, tapPoint);
    if(pointIsInside) 
       NSLog(@"Yeah, i'm a great ios-Developer, i can check if a point is inside a CGRect!");
    

【讨论】:

您已经提供了矩形框架。但我需要检查用户是否在粉红色区域内点击过,并且它的形状不是 Ractangular【参考方案3】:

您应该继承 UIButton 并覆盖它的 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event 区域几何的基础或访问按钮的图像并检查某个点的颜色。

看看这个:OBShapedButton

【讨论】:

UIButton 没有这个方法 如何识别点是否在粉红色区域内?您将如何计算或找到该区域? 在答案中添加您的最后一条评论,以便我接受。我不能接受你目前的回答。

以上是关于如何在 iOS 应用中与 UIButton 的特定区域进行交互的主要内容,如果未能解决你的问题,请参考以下文章