Как добавить UIView в начало всех просмотров?
У меня такой код:
@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];
}
Но это не работает (я хочу видеть Alert над всеми другими видами). Не могли бы вы мне помочь?
Ответы
Ответ 1
Рекомендуемые решения, которые правильно обрабатывают ориентацию устройства,
- pod AGWindowView Он будет автоматически обрабатывать любые вращения и рамки, поэтому вам не придется беспокоиться об этом.
- читайте и следуйте официальному сообщению https://developer.apple.com/library/content/qa/qa1688/_index.html
-
Добавьте свое представление к первому подвью, а не добавьте его в окно
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(v);
view.backgroundColor = UIColor.blackColor()
Ответ 2
Существует еще один метод
Добавьте следующий вид в представлении, который будет отображаться каждый раз, когда контроллер push/pop view
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[[UIApplication sharedApplication] keyWindow] addSubview:<yourViewObject>];
}
И для удаления этого представления в следующем классе добавьте следующие строки кода
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[<yourViewObject> removeFromSuperview];
}
Ответ 3
@MaciekWrocław отвечает быстрой версии
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)!
}
}
Ответ 4
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
Ответ 5
Если вы знаете, что подвью вверху, используйте:
UIView* topMostSubView = <your view top most subview>
[self.view insertSubview:alert aboveSubview:topMostSubView];