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

限于喜欢 提交于 2020-12-02 05:37:07

问题


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!


回答1:


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.




回答2:


You can set the layer's zPosition to -1. That worked for me.




回答3:


I had similar problem (I wanted to prevent border line to be on top of my subviews)

CAShapeLayer * _border = [CAShapeLayer layer];
_border.strokeColor = [UIColor colorWithRed:119/255.0f green:119/255.0f blue:119/255.0f alpha:1.0f].CGColor;
_border.fillColor = nil;
[bgRoundView.layer addSublayer:_border];
_border.path = [UIBezierPath bezierPathWithRoundedRect:bgRoundView.bounds cornerRadius:20.f].CGPath;


来源:https://stackoverflow.com/questions/9901603/calayer-border-is-appearing-above-subview-z-order-related-i-think

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!