Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring a subview to the front when you tap it?

Tags:

ios

I have a view with about 30 subviews on it. I want to add code in my subview's viewcontroller so that when I tap the subview, the subview expands to fill the screen.

I'm using [self.view setFrame:rect] to expand the subview, and this works fine. The problem is that some of the other 29 subviews are above the subview that I just tapped, so they're still visible.

I've tried using bringSubviewToFront from the parent viewcontroller, but this appears to have no effect. Is there any code I can put in my subview's viewcontroller class to make this happen?

like image 433
MusiGenesis Avatar asked Mar 17 '11 21:03

MusiGenesis


People also ask

How do I get Subviews in UIView Swift?

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.

What is Addsubview?

Adds a view to the end of the receiver's list of subviews.


3 Answers

bringSubviewToFront should work, just make sure you're using it correctly. The usage is.

[parentView bringSubviewToFront:childView];
like image 150
seanalltogether Avatar answered Nov 14 '22 17:11

seanalltogether


Use this code, even you don't know about superView:

In objective-c:

[subview.superview bringSubviewToFront: subview];

In swift:

subview.superview?.bringSubview(toFront: subview)
like image 38
Vikram Biwal Avatar answered Nov 14 '22 18:11

Vikram Biwal


For the ease of use an extension in Swift 3

extension UIView {

    func bringToFront() {
        self.superview?.bringSubview(toFront: self)
    }

}
like image 25
Martin Metselaar Avatar answered Nov 14 '22 18:11

Martin Metselaar