How to make a UIView always appear at the front?
Solution 1:
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.
Solution 2:
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:
.