简体   繁体   English

如何完全以编程方式添加UINavigationBar?

[英]How do I add a UINavigationBar completely programmatically?

I'm trying to figure out, given a UIViewController subclass, how to add a UINavigationBar to it. 在给定UIViewController子类的情况下,我试图弄清楚如何向其中添加UINavigationBar All the questions and answers seem to be either embed it in a navigation controller (not possible in this case) or via Storyboard, but I need to do it completely in code. 所有的问题和答案似乎要么嵌入到导航控制器中(在这种情况下是不可能的),要么通过Storyboard嵌入,但是我需要完全在代码中完成。

Do I just add it as a subview of the view controller's view? 我是否只是将其添加为视图控制器视图的子视图? Will it become topLayoutGuide after I pin it to the topLayoutGuide , which would be the status bar prior to adding it? 将其固定到topLayoutGuide ,它会变成topLayoutGuide吗?那是添加它之前的状态栏? Or am I supposed to be setting an attribute on the view controller I cannot figure out, instead of adding it? 还是我应该在无法弄清楚的视图控制器上设置属性,而不是添加它?

Your on the right track, you just add as a subview like you would any other view. 在正确的轨道上,您只需像添加任何其他视图一样将其添加为子视图即可。 The trick to the status bar is setting yourself as the navigationBar delegate and returning UIBarPositioningTopAttached in the delegate method 状态栏的窍门是将自己设置为navigationBar委托,并在委托方法中返回UIBarPositioningTopAttached

.....

self.customNavigationBar.delegate = self;
[self.addSubview self.navigationBar]; 

....

- (UIBarPosition)positionForBar:(id<UIBarPositioning>)bar {
    return UIBarPositioningTopAttached;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM