简体   繁体   中英

How to make a UIView's subviews' alpha change according to it's parent's alpha?

I'm having trouble setting the alpha of some of my subviews.

Using Storyboard, I have a UIView, viewA in my View Controller, with subView1 , subView2 , & subView3 as subviews inside viewA .

When I change viewA 's alpha to 0.5, viewA 's alpha changes but it's subviews' alphas remain the same.

By default, shouldn't it's subview's alpha's change according to it's parents? What am i doing wrong?

Here you go:

self.view.layer.allowsGroupOpacity = YES; 

This will work for all subviews, subviews of subviews and all that.

From the docs:

 * The default value of the property is read from the boolean
 * UIViewGroupOpacity property in the main bundle's Info.plist. If no
 * value is found in the Info.plist the default value is YES for
 * applications linked against the iOS 7 SDK or later and NO for
 * applications linked against an earlier SDK. */

Your project might not be linked against the iOS 7 SDK. If you want this change to work for all views, I'd do this:

  • Go to your .plist
  • Add a row titled "Renders with group opacity"
  • Set it to YES

From Apple's docs:

UIViewGroupOpacity
“Renders with group opacity”
Specifies whether Core Animation layers inherit the opacity of their superlayer. See “UIViewGroupOpacity” for details.
iOS 3.0 and later

那么subView1.alpha = subView1.superview.alpha呢?

Take a look at allowsGroupOpacity , which can be set on the layer. There is also a global info.plist key for changing this behavior app-wide.

When the UIViewGroupOpacity key is not present, the default value is now YES. The default was previously NO.

This means that subviews of a transparent view will first be composited onto that transparent view, then the precomposited subtree will be drawn as a whole onto the background. A NO setting results in less expensive, but also less accurate, compositing: each view in the transparent subtree is composited onto what's underneath it, according to the parent's opacity, in the normal painter's algorithm order

https://developer.apple.com/library/ios/releasenotes/General/RN-iOSSDK-7.0/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM