我想知道如何使用 UIView
属性 clipsToBounds
。
官方文档是这样说的:
clipsToBounds
propertyA Boolean value that determines whether subviews are confined to the bounds of the view.
Discussion
Setting this value toYES
causes subviews to be clipped to the bounds of the receiver. If set toNO
, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value isNO
.
但我不清楚这到底是什么意思。我应该如何使用 clipsToBounds
?将此属性设置为 YES
的后果是什么?还是NO
?
最佳答案
如果我的 super View 是一个每边 10 个单位的盒子,我的 subview 是 20 个单位宽,clipsToBounds
设置为 YES
,我只会看到适合父 View 边界的 subview 的一部分。否则,如果 clipsToBounds
设置为 NO
,我将看到整个 subview ,甚至是父 View 之外的部分(假设我们仍在屏幕上)。
作为一个可视化示例,请考虑在 Storyboard上设置以下 View :
这是一个白色的 UIView
,左上角的标签带有简单的“1”或“2”,因此我可以将它们作为 view1
或 View 2
。此外,黑色 View 与白色 View 的大小相同,但它的原点位于白色 View 的中心。
在 View Controller 的viewDidLoad
方法中,我们有如下代码:
objective-C :
- (void)viewDidLoad {
[super viewDidLoad];
self.view1.clipsToBounds = YES;
self.view2.clipsToBounds = NO;
}
swift :
override func viewDidLoad() {
super.viewDidLoad()
self.view1.clipsToBounds = true
self.view2.clipsToBounds = false
}
当我们运行代码并在模拟器或设备上查看时,我们得到以下结果:
因此,尽管这些 View 设置相同(clipsToBounds
除外),但它们看起来不同。这就是 clipsToBounds
所做的。将其设置为 YES
将提供最佳结果,而将其设置为 NO
将提供最差结果。
如果我们调试 View 层次结构,我们可以更清楚地看到黑框实际上都超出了白色 View 的边界,但只有 View 2 在应用程序实际运行时显示了这一点:
关于ios - clipsToBounds 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449256/