问题描述
我正在尝试将一个按钮的2个角弄成圆形.如果我选择.TopLeft和.BottomLeft像这样:
I'm trying to make 2 corners of a button round. If I select .TopLeft and .BottomLeft like this:
let bezierDisableAdsPath = UIBezierPath(roundedRect: disableAdsButton.bounds, byRoundingCorners: [UIRectCorner.TopLeft , UIRectCorner.BottomLeft] , cornerRadii: CGSizeMake(4.0, 4.0))
let maskAdsLayer = CAShapeLayer()
maskAdsLayer.frame = disableAdsButton.bounds
maskAdsLayer.path = bezierDisableAdsPath.CGPath
disableAdsButton.layer.mask = maskAdsLayer
比代码更漂亮.
如果我选择.TopRight和.像这样的BottomRight:
If I chose .TopRight and . BottomRight like this:
let bezierDisableAdsPath = UIBezierPath(roundedRect: disableAdsButton.bounds, byRoundingCorners: [UIRectCorner.TopRight , UIRectCorner.BottomRight] , cornerRadii: CGSizeMake(4.0, 4.0))
let maskAdsLayer = CAShapeLayer()
maskAdsLayer.frame = disableAdsButton.bounds
maskAdsLayer.path = bezierDisableAdsPath.CGPath
disableAdsButton.layer.mask = maskAdsLayer
比我看不到圆角.这是怎么回事?
than I see no round corners. What is going on here?
我已经尝试过将maskAdsLayer添加为子视图,但这是行不通的.
I already tried adding maskAdsLayer as a subview and it doesn't work.
推荐答案
如果在 viewDidLoad
中执行此操作,则此时可能尚未应用自动布局约束,因此框架您的按钮可能未达到最终值,因此 disableAdsButton.bounds
可能不是您当时所期望的.因此,向右舍入的角可能不可见.您可以通过在代码运行时记录按钮的 bounds
来确认这一点,然后在布局视图后再次查看它.
If you are doing this in viewDidLoad
, the auto layout constraints may not have been applied by this point, and thus the frame of your button may not be at its final value, and thus disableAdsButton.bounds
is probably not what you expect it to be at that point. Thus, the corners that are being rounded to the right may not be visible. You can confirm this by logging the bounds
of the button at the point this code runs and then look at it again after the views have been laid out.
您可以通过将其推迟到 viewDidAppear
或更佳的 viewDidLayoutSubviews
来解决.
You can resolve this by deferring this until viewDidAppear
or, better, viewDidLayoutSubviews
.
这篇关于UIBezierPath:roundedRect:byRoundingCorners:cornerRadii:行为很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!