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;
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.
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.
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.
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:
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With