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

Sia*_*sou 28 iphone objective-c ios

我有这样的代码:

@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];
}
Run Code Online (Sandbox Code Playgroud)

然后我就这样使用它:

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

但它不起作用(我希望看到Alert高于所有其他视图).你可以帮帮我吗?

Mac*_*wia 55

正确处理设备方向的推荐解决方案是

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

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(v);
view.backgroundColor = UIColor.blackColor()
Run Code Online (Sandbox Code Playgroud)

  • 第一种解决方案不尊重设备轮换.如果提供模态视图控制器,则第二种解决方案不起作用. (10认同)

g21*_*2gs 5

还有另一种方法

在视图中添加以下方法将在每次推/弹出视图控制器时添加

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

     [[[UIApplication sharedApplication] keyWindow] addSubview:<yourViewObject>];
}
Run Code Online (Sandbox Code Playgroud)

为了在下一个类中删除此视图,请添加以下代码行

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

    [<yourViewObject> removeFromSuperview];
 }
Run Code Online (Sandbox Code Playgroud)