Search code examples
iosxcodeswiftios8ios8-today-widget

How can I cancel Notification Center Visual Effect (iOS) for an specific view?


I have applied my function applyVibrancy on the viewDidLoad method of my mainViewController for my Today Widget application.

override func viewDidLoad() {
   applyVibrancy()
} 

func applyVibrancy()
{
    let oldView = self.view
    var effectView = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect())

    effectView.frame = oldView.bounds
    effectView.autoresizingMask = oldView.autoresizingMask;

    effectView.userInteractionEnabled = true    
    effectView.contentView.addSubview(oldView)        
    self.view.tintColor = UIColor.clearColor()

    self.view = effectView
 }

This successfully applies this visual effect into my entire widget. But I would like to have some of my nested views (Labels, Buttons, Images, etc) to NOT be affected by this effect.

How can I achieve this?


Solution

  • To achieve the effect you desire, for the views that you want to has this effect, add them to the contentView of a UIVisualEffectView, which then is added as subview of self.view. For other views not to be affected, add them to self.view directly.

    When I run your code, I get a black screen.

    UIVibrancyEffect amplifies and adjusts the color of content layered behind the view, allowing content placed inside the contentView to become more vivid. It is intended to be placed over, or as a subview of, a UIVisualEffectView that has been configured with a UIBlurEffect. This effect only affects content added to the contentView.

    notificationCenterVibrancyEffect is a kind of UIVibrancyEffect, but in your code there is no UIVisualEffectView with a UIBlurEffect configured, you should create one, and place your effectView over that view or add your effectView as subview of that view's contentView. Otherwise you will not see any vibrancy.

    Here is some test code.

    let label = UILabel()
    label.frame = CGRectMake(0, 0, 130, 30)
    label.text = "Has Vibracy!"
    
    let effectView = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect())
    
    effectView.frame = CGRectMake(0, 0, 130, 30)
    effectView.backgroundColor = UIColor.clearColor()
    effectView.userInteractionEnabled = true
    
    effectView.contentView.addSubview(label)
    
    let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
    blurView.contentView.addSubview(effectView)
    blurView.frame = CGRectMake(80, 20, 130, 30)
    
    self.view.tintColor = UIColor.clearColor()
    
    let label1 = UILabel()
    label1.frame = CGRectMake(80, 60, 130, 30)
    label1.text = "No Vibracy!"
    
    self.view.addSubview(blurView)
    self.view.addSubview(label1)