如何单击透明UIView后面的按钮? [英] How can I click a button behind a transparent UIView?

查看:147
本文介绍了如何单击透明UIView后面的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个带有一个子视图的视图控制器。子视图占据屏幕的中心,所有边都有100像素的边距。然后我们添加一些小东西点击里面的子视图。我们只使用子视图来利用新帧(在父视图中,子视图内的x = 0,y = 0实际上是100,100)。

Let's say we have a view controller with one sub view. the subview takes up the center of the screen with 100 px margins on all sides. We then add a bunch of little stuff to click on inside that subview. We are only using the subview to take advantage of the new frame ( x=0, y=0 inside the subview is actually 100,100 in the parent view).

然后,假设我们在子视图后面有一些东西,比如菜单。我希望用户能够在子视图中选择任何小东西,但如果没有什么,我想让触摸通过它(因为背景是清楚的)到它后面的按钮。

Then, imagine that we have something behind the subview, like a menu. I want the user to be able to select any of the "little stuff" in the subview, but if there is nothing there, I want touches to pass through it (since the background is clear anyway) to the buttons behind it.

我该如何做?它看起来像touchesBegan通过,但按钮不工作。

How can I do this? It looks like touchesBegan goes through, but buttons don't work.

推荐答案

为您的容器创建自定义视图并覆盖pointInside:子视图,像这样:

Create a custom view for your container and override the pointInside: message to return NO when the point isn't within an eligible child view, like this:

@interface PassthroughView : UIView
@end

@implementation PassthroughView
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    for (UIView *view in self.subviews) {
        if (!view.hidden && view.alpha > 0 && view.userInteractionEnabled && [view pointInside:[self convertPoint:point toView:view] withEvent:event])
            return YES;
    }
    return NO;
}
@end

使用此视图作为容器将允许任何

Using this view as a container will allow any of its children to receive touches but the view itself will be transparent to events.

编辑:这里是Swift版本

Here is the Swift version

class PassThroughView: UIView {
    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        for subview in subviews {
            if !subview.hidden && subview.alpha > 0 && subview.userInteractionEnabled && subview.pointInside(convertPoint(point, toView: subview), withEvent: event) {
                return true
            }
        }
        return false
    }
}

Swift 3:

class PassThroughView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        for subview in subviews {
            if !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled && subview.point(inside: convert(point, to: subview), with: event) {
                return true
            }
        }
        return false
    }
}

这篇关于如何单击透明UIView后面的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆