是否可以调暗UIView但允许触摸它背后的元素?

时间:2016-02-24 00:35:03

标签: ios uikit

如何在顶部设置灰色叠加层,但允许触摸它下面的按钮?

2 个答案:

答案 0 :(得分:3)

您可以将userInteraction叠加设置为false

答案 1 :(得分:0)

如上所述,您可以将userInteractionEnabled设置为NO

但要注意:当您创建全屏透明视图并将其userInteractionEnabled设置为NO时,该视图的所有子视图都不会是响应用户操作。如果您在视图上添加按钮,它将不会响应用户点击!还有一个问题:如果您将该视图的alpha值设置为透明,例如0.4,那么它的所有子视图也都是透明的!

解决方案很简单:不要在透明视图上放置任何子视图,而是将其他元素添加为视图的兄弟元素。这是Objective-C代码,用于表明我的意思:(注意说明这一切的评论):

//Create a full screen transparent view:
UIView *vw = [[UIView alloc] initWithFrame:self.view.bounds];
vw.backgroundColor = [UIColor greenColor];
vw.alpha = 0.4;
vw.userInteractionEnabled = NO;

//Create a button to appear on top of the transparent view:
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 80, 44)];
btn.backgroundColor = [UIColor redColor];
[btn setTitle:@"Test" forState:UIControlStateNormal];
[btn setTitle:@"Pressed" forState:UIControlStateHighlighted];
//(*) Bad idea: [vw addSubview:btn];

//(**) Correct way to have the button respond to user interaction:
//    Add it as a sibling of the full screen view
[self.view addSubview:vw];
[self.view addSubview:btn];
相关问题