Search code examples
iphonecalayerz-order

CALayer Border is appearing above subview (Z-order related, I think)


I have searched but could not find the reason for this behavior.

I have a UIButton whose image I am setting. Here is how the button should appear. Note that this is just a photoshop of the intended button design:

enter image description here

Essentially, it is a square custom UIButton with a white border and a little surrounding shadow. In the upper right corner, there is a "X" mark, that will be added programmatically as a subview.

Here is the screenshot of the button within the actual app. At this point, I have only added a shadow and the X mark as a subview:

enter image description here

How, when I try to add the white border, here is what it looks like:

enter image description here

It seems that the white border is appearing above the X mark sublayer. I don't know why.

Here is the code that I am using:

// selectedPhotoButton is the UIButton with UIImage set earlier
// At this point, I am adding in the shadow
[selectedPhotoButton layer] setShadowColor:[[UIColor lightGrayColor] CGColor]];
[[selectedPhotoButton layer] setShadowOffset: CGSizeMake(1.0f, 1.0f)];
[[selectedPhotoButton layer] setShadowRadius:0.5f];
[[selectedPhotoButton layer] setShadowOpacity:1.0f]; 

// Now add the white border    
[[selectedPhotoButton layer] setBorderColor:[[UIColor whiteColor] CGColor]];
[[selectedPhotoButton layer] setBorderWidth:2.0];

// Now add the X mark subview
UIImage *deleteImage = [UIImage imageNamed:@"nocheck_photo.png"];
UIImageView *deleteMark = [[UIImageView alloc] initWithFrame:CGRectMake(53, -5, 27, 27)];
deleteMark.contentMode = UIViewContentModeScaleAspectFit;
[deleteMark setImage:deleteImage];
[selectedPhotoButton addSubview:deleteMark];
[deleteMark release];

I don't understand why the border is appearing above the deleteMark subview. Is there any way to get the intended effect?

Thank you!


Solution

  • From Apple's docs on CALayer:

    The border is drawn inset from the receiver’s bounds by borderWidth. It is composited above the receiver’s contents and sublayers and includes the effects of the cornerRadius property.

    In order to get the effect you want, I suggest you put the image into an own subview/sublayer and set that sublayer's borderWidth property.