在窗口或导航控制器上添加视图时,约束会发生变化吗?

时间:2016-10-11 08:25:09

标签: ios objective-c autolayout statusbar

我有一个应用程序,我需要在所有应用程序上显示自定义状态栏。为此,我将此代码写入didFinishLaunchingWithOptions:方法

self.window.windowLevel = UIWindowLevelStatusBar;

然后在viewController中我创建了一个带有(0,0,width,20)框架视图的视图,并添加了一些元素。

我试图在窗口上方添加该视图

AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.statusview setTranslatesAutoresizingMaskIntoConstraints:YES];
[appdelegate.window addSubview:statusview];

但它在左上角添加而没有任何元素。但是当我设置宽度并再次添加元素时,它就会显示出来。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

我认为您的问题是视图的宽度,请确保宽度正确。

如果宽度合适且问题仍然存在,请更新您的代码和屏幕截图。

答案 1 :(得分:0)

- (BOOL)prefersStatusBarHidden {
return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
_statusview.frame = CGRectMake(0, 50, self.view.frame.size.width, 45);
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
_statusview.frame = CGRectMake(0, 0, self.view.frame.size.width, 45);
}

- (void)viewDidLoad {
[super viewDidLoad];
_statusview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
_statusview.backgroundColor = [UIColor blackColor];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.center = _statusview.center;
[btn setTitle:@"button" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor whiteColor]];
[_statusview addSubview:btn];
[_statusview setTranslatesAutoresizingMaskIntoConstraints:YES];
[self.view addSubview:_statusview];
self.view.backgroundColor = [UIColor whiteColor];
}

将代码放在viewdidload中。这就是你想要的吗?