简体   繁体   中英

Removing UIView' backing layer from superLayer

-(void) testLayer {

    UIView *parent = [UIView new];
    UIView *subview1 = [UIView new];
    UIView *subview2 = [UIView new];

    [parent addSubview:subview1];
    [parent addSubview:subview2];

    XCTAssertTrue(subview1.superview != nil);

    XCTAssertTrue([parent.subviews count] == 2);

    [subview1.layer removeFromSuperlayer];

    XCTAssertTrue(subview1.superview == nil);


    XCTAssertTrue([parent.subviews count] == 1); //This test case failing

}

Can someone explain why the last test case is failing? I must be missing something basic here.

I know that [subview1 removeFromSuperview] is the right way to remove it from the superView but I am interested in knowing what is happening here behind the scenes.

My confusion is because subview1.superview is nil after executing [subview1.layer removeFromSuperlayer] but the subviews array still has both subviews in it.

The answer is so obvious: [subview1.layer removeFromSuperlayer] removes a layer whereas in parent.subviews you're calling for 'views'. Since a view and layer are different, the test case fails. As Apple says about removeFromSuperlayer:

You can use this method to remove a layer (and all of its sublayers) from a layer hierarchy. This method updates both the superlayer's list of sublayers and sets this layer's superlayer property to nil

.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM