Bringing a subview to be in front of all other vie

2019-01-16 07:19发布

问题:

I am working on integrating an ad provider into my app currently. I wish to place a fading message in front of the ad when the ad displays but have been completely unsuccessful.

I made a function which adds a subview to my current view and tries to bring it to the front using

[self.view bringSubviewToFront:mySubview]

The function fires on notification that the ad loaded (the notification is from the adprovider's SDK). However, my subview does not end up in front of the ad. I imagine this is made purposely difficult by the ad provider, but I wish to do it regardless. I am currently discussing with the provider whether or not this can be allowed. But for the time being, I just want to see if it's even possible.

Is there anyway I can force a subview of mine to be the top-most view such that it will not be obstructed by anything?

回答1:

What if the ad provider's view is not added to self.view but to something like [UIApplication sharedApplication].keyWindow?

Try something like:

[[UIApplication sharedApplication].keyWindow addSubview:yourSubview]

or

[[UIApplication sharedApplication].keyWindow bringSubviewToFront:yourSubview]


回答2:

try this:

self.view.layer.zPosition = 1;


回答3:

Swift 2 version of Jere's answer:

UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(YourViewHere)

Swift 3:

UIApplication.shared.keyWindow!.bringSubview(toFront: YourViewHere)

Swift 4:

UIApplication.shared.keyWindow!.bringSubviewToFront(YourViewHere)

Hope it saves someone 10 seconds! ;)



回答4:

I had a need for this once. I created a custom UIView class - AlwaysOnTopView.

@interface AlwaysOnTopView : UIView
@end

@implementation AlwaysOnTopView

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.superview && [keyPath isEqual:@"subviews.@count"]) {
        [self.superview bringSubviewToFront:self];
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (self.superview) {
        [self.superview removeObserver:self forKeyPath:@"subviews.@count"];
    }

    [super willMoveToSuperview:newSuperview];
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];

    if (self.superview) {
        [self.superview addObserver:self forKeyPath:@"subviews.@count" options:0 context:nil];
    }
}

@end

Have your view extend this class. Of course this only ensures a subview is above all of its sibling views.



回答5:

As far as i experienced zposition is a best way.

self.view.layer.zPosition = 1;



回答6:

In Swift 4.2

UIApplication.shared.keyWindow!.bringSubviewToFront(yourView)

Source: https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubviewtofront#declarations



回答7:

xamarin ios : this.InsertSubview(subview_youwant_beback, 0);