如何将UIView添加到所有视图的顶部?

30

我有这样的代码:

@interface Alert : UIView 
{

}
/*
- (void) initWithTitle:(NSString*)title message:(NSString*)message cancelButtonTitle:(NSString*)cancelButtonTitle otherButtonTitles:(NSString*)buttonTitle,... delegate:(id)delegate;
*/
@end


@implementation Alert

- (void) drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect); // Очистим context

    CGContextSetRGBFillColor(context, 255, 0, 0, 1);
    CGContextFillRect(context, CGRectMake(20, 20, 100, 100));
}

- (void) show
{
    self.center = [[[UIApplication sharedApplication] keyWindow] center];
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    [[[UIApplication sharedApplication] keyWindow] bringSubviewToFront:self];
}

然后我这样使用它:

- (void)viewDidLoad
{
    [super viewDidLoad];
     Alert * alert = [[Alert alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [alert show];
    [alert release];
}

但是它不起作用(我希望能够在所有其他视图之上看到警报)。你能帮助我吗?

5个回答

57

处理设备方向的推荐解决方案包括:

 UIWindow* window = [UIApplication sharedApplication].keyWindow;
 if (!window) 
     window = [[UIApplication sharedApplication].windows objectAtIndex:0];
 [[[window subviews] objectAtIndex:0] addSubview:myView];

您还可以将其添加到窗口中。但它不会处理设备方向。

let window = UIApplication.sharedApplication().keyWindow!
let view = UIView(frame: CGRect(x: window.frame.origin.x, y: window.frame.origin.y, width: window.frame.width, height: window.frame.height))
window.addSubview(view);
view.backgroundColor = UIColor.blackColor()

10
第一个解决方案不能正确处理设备旋转。第二个解决方案在显示模态视图控制器时无法工作。 - Vladimir Obrizan
1
第二个 iPad 的工作非常好,谢谢 :) - Paresh Navadiya
请查看这个关于Swift 5的答案:https://dev59.com/2VkT5IYBdhLWcg3wefbR#66220162 - Tamás Sengel

5

还有一种方法

在视图即将出现时添加以下方法,以便每次推送/弹出视图控制器时添加

-(void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];

     [[[UIApplication sharedApplication] keyWindow] addSubview:<yourViewObject>];
}

要在下一个类中移除此视图,请添加以下代码

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [<yourViewObject> removeFromSuperview];
 }

1

@MaciekWrocław回答的是Swift版本

Swift2

 var appDelegate = (UIApplication.sharedApplication().delegate! as! AppDelegate)
 var backgrView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
 backgrView.backgroundColor = UIColor.redColor()
 backgrView.alpha = 0.6
 window?.addSubview(backgrView)

Swift3
     var appDelegate: AppDelegate? = (UIApplication.shared.delegate as? AppDelegate)
     var backgrView = UIView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(UIScreen.main.bounds.size.width), height: CGFloat(UIScreen.main.bounds.size.height)))
     backgrView.backgroundColor = UIColor.red
     backgrView.alpha = 0.6
     window?.addSubview(backgrView)

我正在为我的应用程序编写关于网络连接的代码,该代码位于AppDelegate中:

func checkReachabilityUpdateUI() -> Int {

    let remoteHostStatus = self.reachability?.currentReachabilityStatus()


    if remoteHostStatus?.rawValue == 0 {
        let backgrView = UIView(frame: CGRectMake(0, 60, UIScreen.mainScreen().bounds.size.width, 44))

        let statusMessage = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 44))

        statusMessage.text = "No internet Connection"
        statusMessage.textAlignment = .Center
        statusMessage.textColor =  UIColor.whiteColor()

        backgrView.backgroundColor = UIColor.redColor()

        backgrView.addSubview(statusMessage)

        backgrView.tag = 100

        window?.addSubview(backgrView)

        return (remoteHostStatus?.rawValue)!

    }
    else {

        if let viewWithTag = self.window!.viewWithTag(100) {
            print("Tag 100")
            viewWithTag.removeFromSuperview()
        }
        else {
            print("tag not found")
        }

       return (remoteHostStatus?.rawValue)!

    }

}

1
UIView *spinnerView;//This is your view

self.spinnerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];  
//Based on your requirement change width and height like self.view.bounds.size.width
self.spinnerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
// [self.view addSubview:self.spinnerView];
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:self.spinnerView];

在Swift 5中
let window = UIApplication.shared.keyWindow! 
window.addSubview(self.spinnerView) // Add your view here

一个更简单的解决方案是:

yourViewName.layer.zPosition = 1//Here fix your view name

1
zPosition救了我。因为我有很多容器子视图,每个容器里面都有tableview和更多的子视图。谢谢@Naresh - KrishnDip

-4
如果您知道顶部的子视图是什么,请使用以下代码:
UIView* topMostSubView = <your view's top most subview>
[self.view insertSubview:alert aboveSubview:topMostSubView];

这是一个很大的假设。 - Lino Silva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接