添加子视图后,不能点击UIButton

我正在使用一种方法为我的button添加阴影。 问题是在那之后,我不能点击它们。 我将userinteractionenabled属性添加到YES,但仍然无法点击。

这是代码。

我该如何解决? 我错过了什么吗?

- (UIView*)putView:(UIView*)view insideShadowWithColor:(UIColor*)color andRadius:(CGFloat)shadowRadius andOffset:(CGSize)shadowOffset andOpacity:(CGFloat)shadowOpacity { CGRect shadowFrame; // Modify this if needed shadowFrame.size.width = 0.f; shadowFrame.size.height = 0.f; shadowFrame.origin.x = 0.f; shadowFrame.origin.y = 0.f; UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame]; shadow.userInteractionEnabled = YES; // Modify this if needed shadow.layer.shadowColor = color.CGColor; shadow.layer.shadowOffset = shadowOffset; shadow.layer.shadowRadius = shadowRadius; shadow.layer.masksToBounds = NO; shadow.clipsToBounds = NO; shadow.layer.shadowOpacity = shadowOpacity; [view.superview insertSubview:shadow belowSubview:view]; [shadow addSubview:view]; return shadow; } 

我find解决scheme

经过人们的评论,我做了一些改变。 这是最终的代码

 + (void)putView:(UIView*)view insideShadowWithColor:(UIColor*)color andBlur:(CGFloat)shadowRadius andOffset:(CGSize)shadowOffset andOpacity:(CGFloat)shadowOpacity { CGRect shadowFrame = view.frame; UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame]; shadow.backgroundColor = [UIColor redColor]; shadow.userInteractionEnabled = YES; // Modify this if needed shadow.layer.shadowColor = color.CGColor; shadow.layer.shadowOffset = shadowOffset; shadow.layer.shadowRadius = shadowRadius; shadow.layer.cornerRadius = view.layer.cornerRadius; shadow.layer.masksToBounds = NO; shadow.clipsToBounds = NO; shadow.layer.shadowOpacity = shadowOpacity; [view.superview insertSubview:shadow belowSubview:view]; } 

有了这个,您可以同时看到带有圆angular和阴影的视图。 而且,当然,触摸事件启用!

这是有道理的,因为你已经把UIView放在button的上面,这意味着你不能访问那个button。 你已经在UIView上设置了UserInteractionEnabled ,但这没用,因为你没有要求UIView响应触摸事件。 在这个例子中,我会build议添加一个UIGestureRecognizer到UIView,而不是试图把一个UIView放在button上。

 CGRect shadowFrame; // Modify this if needed shadowFrame.size.width = 0.f; shadowFrame.size.height = 0.f; shadowFrame.origin.x = 0.f; shadowFrame.origin.y = 0.f; UIView * shadow = [[UIView alloc] initWithFrame:shadowFrame]; 

在上面的代码中,你有一个0,0,0,0帧的视图。 那么你怎么能点击它?