Subview appears underneath superviews layer.border?

10,085

Solution 1

According to the Apple specification: It is composited above the receiver’s contents and sublayers.

So, the border will always be above of all your subviews, even if you bring your subview to the front and so on.

So I make a background view to fake the border.

E.g.:

UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
backgroundView.backgroundColor = [UIColor blackColor];
backgroundView.clipsToBounds = NO;

UIView *bView = [[UIView alloc] initWithFrame:CGRectInset(backgroundView.bounds, 3, 3)];
bView.backgroundColor = [UIColor redColor];

UIView *cView = [[UIView alloc] initWithFrame:CGRectMake(-50, -50, 100, 100)];
cView.backgroundColor = [UIColor yellowColor];
[bView addSubview:cView];

[backgroundView addSubview:bView];

[self.window addSubview:backgroundView];

and the effect:

enter image description here

Solution 2

Depending on your view structure, it might be easier to add the subview to the parent of your main view. It can then overlap the main view and will overlay the border as you requested.

Share:
10,085
Ser Pounce
Author by

Ser Pounce

merge me

Updated on June 06, 2022

Comments

  • Ser Pounce
    Ser Pounce almost 2 years

    I have a UIView in which I define it's border in the following manner:

    self.layer.borderColor = [UIColor blackColor].CGColor;
    self.layer.borderWidth = 3;
    

    I attach a subview to this UIView, and when I move the subview over the border, it goes underneath it. Is this the intended behavior? Is there anyway to make the subview go on top of it?

  • Ser Pounce
    Ser Pounce about 11 years
    I need it to be set to no because this view goes outside of its superviews bounds.
  • Ser Pounce
    Ser Pounce about 11 years
    I think also could make a view that holds the border view, and the view that's suppose to go on top of it as subviews, then make the sure the border view is attached first.
  • Guo Luchuan
    Guo Luchuan about 11 years
    @StackOverFlowRider yes you can make a CustomView , and its .view is the border , and CustomView has a UIView property can named yourView. the yourView is your real useful view , and yourView is a subview of the CustomView.view
  • Ser Pounce
    Ser Pounce about 11 years
    Thanks for that answer btw.
  • Rambatino
    Rambatino over 9 years
    Make sure to set the #exclusiveTouch# and #userInteractionEnabled# properties of the subview to NO to pass the touch events to the button itself (interactivelogic.net/wp/2011/07/…)
  • Scott Zhu
    Scott Zhu over 3 years
    This way you won't be able to set a clear background