【问题标题】:Adding 1pt Bar under navigation bar在导航栏下添加 1pt Bar
【发布时间】:2018-01-16 01:32:24
【问题描述】:

我像这样创建了一个视图,我想将它放在导航栏的正下方,但我添加的约束什么都不做,并且一直将导航栏保持在视图的顶部。

_navSeparator = [[UIView alloc]initWithFrame: CGRectMake(0, 0, 
                 self.view.frame.size.width, 1)];
_navSeparator.backgroundColor = 
                          [UIColor darkColorTheme];
[self.view addSubview:_navSeparator];
[self.view addConstraint:[NSLayoutConstraint 
      constraintWithItem:_navSeparator attribute:NSLayoutAttributeTop 
      relatedBy:NSLayoutRelationEqual toItem:topGuide 
      attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];

它有一些任意的导航标题。

【问题讨论】:

    标签: ios objective-c cocoa-touch


    【解决方案1】:

    如果您想使用 AutoLayout,请设置您的视图的translatesAutoresizingMaskIntoConstraints NO。然后Constraint 将起作用并且框架将无用。

    所以我们应该添加完整的约束(前导、顶部、尾随、高度),例如:

    _navSeparator = [[UIView alloc] init];
    _navSeparator.translatesAutoresizingMaskIntoConstraints = NO;
    _navSeparator.backgroundColor =
    [UIColor blackColor];
    
    [self.view addSubview:_navSeparator];
    [self.view addConstraint:[NSLayoutConstraint
                              constraintWithItem:_navSeparator attribute:NSLayoutAttributeTop
                              relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide
                              attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint
                              constraintWithItem:_navSeparator attribute:NSLayoutAttributeLeading
                              relatedBy:NSLayoutRelationEqual toItem:self.view
                              attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint
                              constraintWithItem:_navSeparator attribute:NSLayoutAttributeTrailing
                              relatedBy:NSLayoutRelationEqual toItem:self.view
                              attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [_navSeparator addConstraint:[NSLayoutConstraint
                              constraintWithItem:_navSeparator attribute:NSLayoutAttributeHeight
                              relatedBy:NSLayoutRelationEqual toItem:nil
                              attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:1.0]];
    

    另外iOS11+请修改topGuide为self.view.safeAreaLayoutGuide,因为在文档中我们知道

    使用 view.safeAreaLayoutGuide.topAnchor 代替 topLayoutGuide.bottomAnchor

    另一件事是,如果您确实想要一个高度为 1pt 的视图。您可以设置其高度约束的常量,例如1.0 / [UIScreen mainScreen].scale

    【讨论】:

    • safeAreaLayoutGuide 仅适用于 iOS 11,对吗?
    • @humbleCoder 是的,它是为 iPhone X 设计的
    • 那么对于没有 iphone X 的人来说是看不到吗?顺便说一句,它起作用了。不过我使用了 topLayoutGuide。
    猜你喜欢
    • 2015-05-25
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 2011-02-04
    • 1970-01-01
    相关资源
    最近更新 更多