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

Ios

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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

[parentView bringSubviewToFront:childView];

Solution 2 - Ios

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

In objective-c:

[subview.superview bringSubviewToFront: subview];

In swift:

subview.superview?.bringSubview(toFront: subview)

Solution 3 - Ios

For the ease of use an extension in Swift 3

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

Solution 4 - Ios

In Objective-C:

[self.superview bringSubviewToFront: subview];

In Swift 2.3:

self.superview!.bringSubviewToFront(subview)

In Swift 3.1.1 - Swift 4.1:

superview.bringSubview(toFront: subview)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMusiGenesisView Question on Stackoverflow
Solution 1 - IosseanalltogetherView Answer on Stackoverflow
Solution 2 - IosVikram BiwalView Answer on Stackoverflow
Solution 3 - IosMartin MetselaarView Answer on Stackoverflow
Solution 4 - IosRohan DaveView Answer on Stackoverflow