Akshay Phulare
Akshay Phulare

Reputation: 1599

Shadow Effect not working with Resizable NSView

I have written below code for shadow effect for my NSView.

    [_nsview setWantsLayer:YES];
    _nsview.layer.masksToBounds = NO;
    _nsview.layer.cornerRadius = 5;
    _nsview.layer.shadowOffset = CGSizeMake(.3f, -.3f);
    _nsview.layer.shadowRadius = 10;
    _nsview.layer.shadowOpacity = 0.20; 
    _nsview.layer.shadowColor = [NSColor blackColor].CGColor;

_nsview is outlet of that NSView. Above code works perfectly and gives shadow effect...But problem is that after resizing _nsview shadow getting hide.

This is after running my sample app, shadow effect working perfectly

This is after resizing main window of sample app(_nsview has auto layout constraints, due to that it will also resize with main window)

Upvotes: 1

Views: 552

Answers (2)

Dev Sanghani
Dev Sanghani

Reputation: 1145

Use NSShadow instead:

    [_childView setWantsLayer:YES];
    _childView.layer.backgroundColor = [NSColor whiteColor].CGColor;
    _childView.layer.cornerRadius = 5;

    NSShadow *dropShadow = [[NSShadow alloc] init];
    [dropShadow setShadowColor:[NSColor colorWithWhite:0.1 alpha:0.6]];
    [dropShadow setShadowOffset:NSMakeSize(0, -5)];
    [dropShadow setShadowBlurRadius:5];
    _childView.shadow = dropShadow;

Upvotes: 2

user2994359
user2994359

Reputation: 400

Unless you're using a layer-hosting view (note: different from a layer-backed view) then you should assume that NSView can change layer properties at any time behind the scenes. Shadows and transforms are the most common properties to change outside of the developer's control.

Here is some useful reading:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/SettingUpLayerObjects/SettingUpLayerObjects.html

https://www.objc.io/issues/14-mac/appkit-for-uikit-developers/

Upvotes: 0

Related Questions