I want to have rounded corners and shadow on a UIBarButtonItem
.
UIButton *useButton = [UIButton buttonWithType:UIButtonTypeCustom];
Then I try to set shadow and rounded corners:
useButton.layer.masksToBounds = NO;
useButton.layer.cornerRadius = 4;
useButton.layer.shadowOffset = CGSizeMake(0, 1.5);
useButton.layer.shadowRadius = 0.5;
useButton.layer.shadowOpacity = 1.0;
useButton.layer.shadowColor = [BSTCMColorUtility colorFromHexString:@"#AFAFAF"].CGColor;
Finally I make the UIBarButtonItem
:
UIBarButtonItem *useItem = [[UIBarButtonItem alloc] initWithCustomView:useButton];
[self.navigationItem setRightBarButtonItems:@[useItem]];
I get no rounded corners, but I do get the shadow.
If I add:
useButton.clipsToBounds = YES;
And/or:
useButton.layer.masksToBounds = YES;
I get rounded corners, but no shadow. So I thought that I would try to add a sublayer.
CALayer *useButtonShadowLayer = [CALayer new];
useButtonShadowLayer.frame = useButton.frame;
useButtonShadowLayer.cornerRadius = 4;
useButtonShadowLayer.backgroundColor = [UIColor whiteColor].CGColor;
useButtonShadowLayer.shadowOffset = CGSizeMake(0, 1.5);
useButtonShadowLayer.shadowRadius = 0.5;
useButtonShadowLayer.shadowOpacity = 1.0;
useButtonShadowLayer.shadowColor = [BSTCMColorUtility colorFromHexString:@"#AFAFAF"].CGColor;
useButton.layer.cornerRadius = 4;
useButton.layer.masksToBounds = YES;
UIView *parent = useButton.superview;
[parent.layer insertSublayer:useButtonShadowLayer below:useButton.layer];
It doesn't seem to work, I see no shadow. I get rounded corners tho.
Isn't possible to have rounded corners AND shadow on a UIBarButtonItem
/UIButton
?
Best Answer
Try this Updated code :