如何在导航栏上添加UIView?

时间:2013-01-09 09:44:49

标签: ios objective-c uiview uinavigationbar

我需要与UINavigationBar叠加UIView,例如

http://screencast.com/t/ZKXNFcAzVu

有没有办法做到这一点,除了使用自定义UIView按钮返回导航栏?

5 个答案:

答案 0 :(得分:24)

您可以将子视图添加到应用程序的基本视图

[[[UIApplication sharedApplication] keyWindow] addSubview:vMyCustomUIView];

要确保仅在视图控制器可见时显示,您可以在viewDidAppearviewDidDisappear委托方法中添加和删除它。这是一个显示与它们重叠的蓝色框的示例。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.    
    vTestView = [[UIView alloc] initWithFrame:CGRectMake(10.0f,
                                                         10.0f,
                                                        100.0f,
                                                        100.0f)];
    vTestView.backgroundColor = [UIColor blueColor];
}


-(void)viewDidAppear:(BOOL)animated
{
    [[[UIApplication sharedApplication] keyWindow] addSubview:vMyCustomUIView];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [vMyCustomUIView removeFromSuperview];
}

答案 1 :(得分:13)

使用方法:

- (void)bringSubviewToFront:(UIView *)view

所以在你的情况下将是:

[navigationBar addSubview:myRibbon];
[navigationBar bringSubviewToFront:myRibbon];

另外请不要忘记,除非您这样做,否则您的功能区将不会完全显示:

navigationBar.clipsToBounds = NO;

答案 2 :(得分:1)

我隐藏了NavigationBar并添加了UIView。它看起来与Navbar相同。 然后添加一个带红色书签的UIView。除此之外,还可以单独触摸书签动画。

如果我这样添加书签: [navigationBar addSubview:myRibbon]; 它隐藏在一半大小

答案 3 :(得分:0)

这是Swift 3的回答

UIApplication.shared.keyWindow?.addSubview(menuView)

答案 4 :(得分:0)

这是我的实现方式,希望对您有所帮助。

  override func viewWillAppear(_ animated: Bool) {
    let testView = UIView(frame: .zero)
    testView.backgroundColor = .black
    testView.layer.cornerRadius = 10
    testView.translatesAutoresizingMaskIntoConstraints = false
    self.navigationController?.navigationBar.addSubview(testView)
    NSLayoutConstraint.activate([
      testView.widthAnchor
        .constraint(equalToConstant: 50),
      testView.heightAnchor
        .constraint(equalToConstant: 70),
      testView.topAnchor
        .constraint(equalTo: (self.navigationController?.navigationBar.topAnchor)!),
      testView.trailingAnchor
        .constraint(equalTo: (self.navigationController?.navigationBar.trailingAnchor)!, constant: -20)
      ])
    self.customView = testView
  }
  
  // i dont need to display the overlay in every page
  // so i remove it everytime i navigate to a new page
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.customView.removeFromSuperview()
  }

navigation bar overlay