【问题标题】:Constraints getting changed when adding a view over window or navigation controller?在窗口或导航控制器上添加视图时约束发生变化?
【发布时间】:2016-10-11 08:25:09
【问题描述】:

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

self.window.windowLevel = UIWindowLevelStatusBar;

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

我正在尝试像这样在窗口上方添加该视图

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

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

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: ios objective-c autolayout statusbar


    【解决方案1】:

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

    如果宽度合适,问题依旧,请更新你的代码和截图。

    【讨论】:

    • 我也添加了宽度约束,当我添加这一行时 statusview.frame=CGRectMake(0, 0, self.view.frame.size.width, 20);里面的元素不是显示
    • 将 self.view.frame.size.width 改为 [uiscreen mainscreen].bounds.size.width ,再试一次。
    • 相同的结果。正确添加但缺少内部元素
    • 能否更新更多的 didFinishLaunchingWithOptions 方法代码。
    • 我在视图控制器中执行此操作,属性为 view.nothing there.just a return yes
    【解决方案2】:
    - (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。这就是你想要的吗?

    【讨论】:

    • 其实在窗口上方或者在视图上方,效果是一样的。
    • 如果你需要视图总是高于所有视图,你只需要一个父控制器,所有子控制器都继承父类。
    • 如果我设置了框架,那么它不会显示内部元素。我已经告诉你了
    • 你能告诉我你是如何在视图中制作元素的吗?我更改代码并进行测试,当我触摸开始或触摸结束按钮时,总是在状态视图的内部。
    猜你喜欢
    • 2013-06-21
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2016-11-30
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多