Avba
Avba

Reputation: 15276

Can a UIView know when it is on screen

I have a UIView with a lot of components enclosed in it and would like to update some of them if the view is removed or if its parent view controller is popped/pushed. Is it possible for a UIView to get this information

Similar to the method in UIViewController

-(void)viewWillAppear;

Would like something like

-(void)UIViewWillAppear;

Edit for some comments I saw:

I'll explain a bit more

But I have a special case where the UIView needed to add a "floating view" on top of itself (Imagine a zooming/panning/scrolling UISCrollView subclass with floater on top of itself) such that when it scrolled the floating view stayed in place relative to the superview. I tried recalculating the new origin of the "floater" inside of the -(void)layoutSubviews method but the re-placement was very choppy. In order to solve this choppyness problem, the custom UIView added the floating view (which in theory is its subview) as a subview for its superview (a bit of a tongue twister :) ). Now arises a problem when the custom UIView is removed (or its containing view controller is pushed offscreen). How can the special UISCrollView remove the floating view from its superView.

Upvotes: 5

Views: 1816

Answers (3)

Leonardo
Leonardo

Reputation: 9857

The UIView class reference has some kvo observing change.

By implementing -(void)willRemoveSubview:(UIView *)subview you could see the other way round.

UPDATE After reading the explanations:

I hope I understood correctly. I did something similiar time ago, but with a UITableView rather than a UIScrollView (but they are quite the same underneath).

It was like a popup detail view. I solved, as you already did, by adding the detail view to the UITableView superview, and then I added a close UIButton in the detail view, with a corresponding IBOutlet:

@interface CustomUIView : UIView

@property(nonatomic,weak) IBOutlet UIButtonView *closingButton;

-(void)closeDetail:(IBAction)action;

@end

and the action was just:

-(void)closeDetail:(IBAction)action {
   // do your cleaning/change to the detail subviews
   [self removeFromSuperview]; // <-- clsoe the detail view
}

sdsds

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

You can override willMoveToSuperview: to find out when a view is inserted into a hierarchy and when it's removed. That's probably not what you want since the view can be part of a hierarchy and not be inserted by itself.

To find out if it's on screen use willMoveToWindow:. If the argument is non-nil the view just became part of a visible view hierarchy.

If you need to do something after the change use didMoveToWindow:.

Upvotes: 2

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

UIView do not appear/disappear 'randomly' or when they want - your view controllers (or code) control this. So you should find out when you show them, and call code you need.

Upvotes: 0

Related Questions