为什么遮罩在 UISearchBar 上不起作用
我正在尝试在 UISearchBar 的左上角和右上角添加圆角。
但是,我发现遮罩层在 UISearchBar 上不起作用,无论我如何设置它。
这是我的代码
// UIView* bar = [searchBar_.subviews objectAtIndex:0]; // try to add mask to background view but also failed
UIView* bar = searchBar_;
CGRect toolbarBounds = bar.bounds;
CAShapeLayer *maskLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect: toolbarBounds
byRoundingCorners:UIRectCornerTopLeft
cornerRadii:CGSizeMake(5.0f, 5.0f)];
[maskLayer setPath:[path CGPath]];
[maskLayer setFillColor:[[UIColor greenColor] CGColor]];
bar.layer.masksToBounds = YES;
bar.layer.mask = maskLayer;
我也尝试过“剪辑子视图”,但它也不起作用。
然后我尝试更多,我只是将背景视图(子视图 0)设置为隐藏。令我惊讶的是,它仍然可见。
UISearchBar有什么魔力吗? 该遮罩确实适用于 UIToolbar。
I am trying to add round corner to UISearchBar at the top-left and top-right corners.
However, I found the mask layer doesn't work on UISearchBar, no matter how I set it.
Here is my code
// UIView* bar = [searchBar_.subviews objectAtIndex:0]; // try to add mask to background view but also failed
UIView* bar = searchBar_;
CGRect toolbarBounds = bar.bounds;
CAShapeLayer *maskLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect: toolbarBounds
byRoundingCorners:UIRectCornerTopLeft
cornerRadii:CGSizeMake(5.0f, 5.0f)];
[maskLayer setPath:[path CGPath]];
[maskLayer setFillColor:[[UIColor greenColor] CGColor]];
bar.layer.masksToBounds = YES;
bar.layer.mask = maskLayer;
I have also tried the "Clip subviews", but it doesn't work either.
Then I try something more, I just set the background view (subview 0) hidden. To mu surprise, it is still visible.
Is there any magic in the UISearchBar?
The mask does work on UIToolbar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题可能与
mask
属性的实现方式有关。如果将遮罩层添加到已经属于层次结构一部分的层,则它将不起作用。 CALayer 的文档说:在添加遮罩层之前,您必须从其
超级视图
中删除搜索栏。像这样换行最后一行:如果您愿意,还可以使用
removeFromSuperlayer
和addSublayer:
。另外,如果您的搜索栏不是层次结构中的最顶层视图,请确保找到它的位置,并使用insertSubview:atIndex:
或类似方法之一将其放回正确的位置。Your problem could be related to how the
mask
property is implemented. It will not work if you add a mask layer to a layer which is already part of a hierarchy. The docs forCALayer
say:You'll have to remove the search bar from its
superview
before adding the mask layer. Wrap your last line like so:You can also use
removeFromSuperlayer
andaddSublayer:
if you prefer. Also, if your search bar isn't the topmost view in your hierarchy, make sure to find out where it is and put it back in the right place usinginsertSubview:atIndex:
or one of the similar methods.