Is it possible to dim a UIView but allow touch of elements behind it?

久未见 提交于 2019-12-31 01:25:13

问题


How would you have a grey overlay on top, but allow to touch buttons beneath it?


回答1:


You can set userInteraction of overlay to false.




回答2:


As mentioned, you can set userInteractionEnabled to NO.

But pay attention: when you create a full screen transparent view, and set its userInteractionEnabled to NO, all the subviews of that view will not be responsive to user actions. If you add a button on your view, it will not respond to user taps! and another problem: if you set the alpha value of that view to be transparent, e.g. 0.4, then all its subviews will be transparent too!

The solution is simple: don't put any subview on your transparent view, but instead, add your other elements as siblings of your view. Here is Objective-C code to show what I mean: (notice the comments which say it all):

//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];


来源:https://stackoverflow.com/questions/35591090/is-it-possible-to-dim-a-uiview-but-allow-touch-of-elements-behind-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!