简体   繁体   中英

Make a UIView change its superview (or superview's superview)?

I have four UIView s: viewA is the root view, vhich has viewB as its subview. viewB has viewC as its subview and viewC has viewD as its subview. So there is a hierarchy of four views. viewD is basically a button that can be tapped to do something. Because the operation has to do with database, it may takes a while. So I want a dark opaque UIView with a UIActivityIndicator at the center to tell the user to wait for a moment and prevent other tapping action that may cause trouble. However, the dark view has to be put in viewA to make it cover all the screen. Here are what I tried (and succeeded) but I want to know whether there are any easier ways to do it.

  1. Access viewA from viewD by viewD.superview.superview.superview . However it's not very flexible because once the hierarchy is changed, this chain is likely to be changed.

  2. Use delegation. viewD.delegate = viewA . However, viewD is created by viewC (its direct superview) which is created by viewB , which is created by viewA . So if viewD , viewC , and viewB are not @property of its respective superclass (accessing by viewA.viewB.viewC.viewD is not possible), then viewA cannot have a pointer to viewD , which will make the delegation impossible (as far as I understand).

  3. Use NSNotification . Make viewD post a @"ActivityIndicatorShouldBePutOn" notification and make viewA an observer of it. However, NSNotification is used for broadcasting right? So it is somewhat inappropriate.

  4. As long as this case goes (the dark mask is put on the whole screen), I can use something related to UIApplication to access the screen and put it direct onto it. But if I want to put it only on a part of a screen for a different purpose, then this is not going to work.

So I want to ask whether there is a better way of doing it or whether one method mentioned above is the standard way.

You can add the activity indicator view to the main window. You can get the keyWindow using:

[[UIApplication sharedApplication] keyWindow];

I would recommend this API MBProgressHUD . It has a good look and feel and is dead easy to use:

在此处输入图片说明

Displaying the activityIndicator

[MBProgressHUD showHUDAddedTo:self.view animated:YES];

Removing it

[MBProgressHUD hideHUDForView:self.view animated:YES];

you can use option 3 even though its a broadcast, you can listen to it with only 1 observer. then just have different notifications for each UIView

I would say that is the easiest/guaranteed fix even though it may not be elegant, nothing wrong with it imo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM