Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a UIView always appear at the front?

Tags:

iphone

uiview

Currently I have a UIView which contains some controls. I then have some images I programatically add to the view to display as animations. Currently at the end of each interval of my game loop im having to tell the controller to move the UIView control to the front, otherwise the images will appear on top of it. Is there a less costly method of making it persist as always on top.

Currently I have the following at the end of my game loop:

[self.view bringSubviewToFront:myControlView]; 

Could I do something like this when the game initiates:

myControlView.alwaysOnTop = true; 
like image 723
woot586 Avatar asked Jun 28 '11 18:06

woot586


People also ask

What is the difference between UIView and UIViewController?

They are separate classes: UIView is a class that represents the screen of the device of everything that is visible to the viewer, while UIViewController is a class that controls an instance of UIView, and handles all of the logic and code behind that view.

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.


2 Answers

Objective-C

#import <QuartzCore/QuartzCore.h> myAlwaysOnTopView.layer.zPosition = MAXFLOAT; 

Swift 2

myAlwaysOnTopView.layer.zPosition = .max 

Swift 3

myAlwaysOnTopView.layer.zPosition = .greatestFiniteMagnitude 

Swift 5.3

view.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude) 

This solution is better, especially if you want your view to be always on top, regardless of other views added after it. Just add any other view using addSubview: and it will always remains on top.

IMPORTANT: this solution will make the UIView appear on top, but it will still be below other views for the UI system. That is, any user interaction with the view will generally not work, because it is handled by other overlapping views first.

like image 134
Muhammad Hassan Nasr Avatar answered Sep 25 '22 06:09

Muhammad Hassan Nasr


Rather than using -addSubview: to insert your images, use -insertSubview:belowSubview: and pass your UIView as the second parameter:

[self.view insertSubview:myImage belowSubview:myControlView]; 

Note that for similar purposes you also have access to the methods -insertSubview:aboveSubview: and -insertSubview:atIndex:.

like image 41
Seamus Campbell Avatar answered Sep 21 '22 06:09

Seamus Campbell