How does clipsToBounds work?

三世轮回 提交于 2019-11-26 21:34:05

If my superview is a box measuring 10 units on each side, and my subview is 20 units wide, with clipsToBounds set to YES, I'll only see the part of the subview that fits within the bounds of the superview. Otherwise, if clipsToBounds is set to NO, I'll see the entire subview, even the parts outside the superview (assuming we're still on the screen).

As a visual example, consider the following views set up on the storyboard:

This is a white UIView, a label in the top left corner with either a simple "1" or "2" so that I can discuss these as view1 or view2. Additionally, the black view is the same size as the white view, but it's origin is at the white view's center.

In the view controller's viewDidLoad method, we have the following code:

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
}

When we run the code and look at in the simulator or on the device, we get the following results:

So, despite these views being set up identically (except clipsToBounds), they look different. This is what clipsToBounds does. Setting it to YES will provide the top result, while setting it to NO provides the bottom result.

If we debug the view hierarchy, we can see more clearly that the black boxes both do actually extend past the boarders of the white view, but only view 2 shows this when the app is actually running:

uiview and textfield with shadow Swift 4

self.txtCurrent.layer.shadowOpacity = 0.5
self.txtCurrent.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)          
self.txtCurrent.layer.shadowRadius = 5.0
self.txtCurrent.layer.shadowColor = UIColor.black.cgColor
self.txtCurrent.layer.masksToBounds = false

uiview with shadow

self.yourview.layer.shadowOpacity = 0.5
self.yourview.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
self.yourview.layer.shadowRadius = 5.0
self.yourview.layer.shadowColor = UIColor.black.cgColor
self.yourview.layer.masksToBounds = false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!