17

我已经搜索但找不到这种行为的原因。

我有一个 UIButton 我正在设置其图像。这是按钮的显示方式。请注意,这只是预期按钮设计的 Photoshop:

在此处输入图像描述

本质上,它是一个方形的自定义 UIButton,带有白色边框和一点周围的阴影。在右上角,有一个“X”标记,它将以编程方式添加为子视图。

这是实际应用程序中按钮的屏幕截图。此时,我只添加了一个阴影和 X 标记作为子视图:

在此处输入图像描述

如何,当我尝试添加白色边框时,它看起来像这样:

在此处输入图像描述

似乎白色边框出现在 X 标记子图层上方。我不知道为什么。

这是我正在使用的代码:

// 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];

我不明白为什么边框出现在 deleteMark 子视图上方。有什么办法可以达到预期的效果吗?

谢谢!

4

3 回答 3

18

来自 Apple 的文档CALayer

边框是从接收者的边界以borderWidth 绘制的。它复合在接收器的内容和子层之上,并包含cornerRadius 属性的效果。

为了得到你想要的效果,我建议你把图像放到一个自己的子视图/子层中,并设置该子层的borderWidth属性。

于 2012-03-28T07:35:09.067 回答
4

您可以将图层的 zPosition 设置为 -1。这对我有用。

于 2016-10-26T23:33:20.560 回答
2

我有类似的问题(我想防止边界线出现在我的子视图之上)

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;
于 2014-09-12T10:47:31.740 回答