我有一个侧边菜单,可以滑出显示表视图,然后从那里使用揭示视图控制器进行Segue。这个Segue必须直接连接到视图控制器;我不能使用导航控制器。
如何在没有导航控制器的情况下添加带有工具栏按钮的导航栏?
我有一个侧边菜单,可以滑出显示表视图,然后从那里使用揭示视图控制器进行Segue。这个Segue必须直接连接到视图控制器;我不能使用导航控制器。
如何在没有导航控制器的情况下添加带有工具栏按钮的导航栏?
viewWillAppear
中编写了以下代码(注意 - viewDidLoad
也可以,但不建议)- 所以,您拥有一个没有导航控制器的白色导航栏和蓝色栏按钮项。同样,在您的情况下实现它的其他方法。希望这能有所帮助。UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,10,32,32)];
[myImage setImage:[UIImage imageNamed:@"image.png"]];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myImage];
[self.view addSubview:myImage];
Swift 4 版本
let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
navigationBar.barTintColor = UIColor.lightGray
view.addSubview(navigationBar)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: nil)
let navigationItem = UINavigationItem(title: "Title")
navigationItem.leftBarButtonItem = cancelButton
navigationItem.rightBarButtonItem = doneButton
navigationBar.items = [navigationItem]
有一个方法可以在接口构建器中使用 NavigationItem
来实现这一点。
首先,在接口构建器中为你的 ViewController
添加一个 NavigationItem
,就像你使用 NavigationController
时一样。确保通过选择除了“推断”和“无”之外的其他东西来使 NavigationBar
可见,以模拟指标。
其次,在 viewDidLoad
中,只需添加以下几行即可:
- (void)viewDidLoad
{
[super viewDidLoad];
UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame: frame];
bar.items = @[self.navigationItem];
[self.view addSubview: bar];
}
对于 frame
,width
将与您的 ViewController
相同,而 height
将是 44.0
或 64.0
,具体取决于 status bar
是否可见。
CGFloat navigationBarHeight = 44.f + [UIApplication sharedApplication].statusBarFrame.size.height;
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, navigationBarHeight);
如果您希望支持不同的方向,请使用NSLayoutConstraints
:
CGFloat navigationBarHeight = 44.f + [UIApplication sharedApplication].statusBarFrame.size.height;
[self.view addConstraints: @[
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeLeft
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeLeft
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeRight
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeRight
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeTop
relatedBy: NSLayoutRelationEqual
toItem: bar
attribute: NSLayoutAttributeTop
multiplier: 1.0
constant: 0.0],
[NSLayoutConstraint constraintWithItem: bar
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 1.0
constant: navigationBarHeight],
]];
var myNav: UINavigationBar?
2) 测试是否已设置:
viewWillAppear:(BOOL)animated {
if self.myNav != nil{
return
}
self.myNav = ....
3) 确保移除现有的控制器,例如在didDisappear中...
注意...指定大小是不正确的。如果iOS旋转,则无法正常工作。