如何将导航栏添加到视图控制器(实际上是集合视图控制器),而视图控制器没有嵌入导航控制器?我试着将导航栏拖到视图上,但它就是粘不住。这是在Swift中。
0lvr5msh1#
请尝试将以下代码放入viewDidLoad:
viewDidLoad
let height: CGFloat = 75 let navbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height)) navbar.backgroundColor = UIColor.whiteColor() navbar.delegate = self let navItem = UINavigationItem() navItem.title = "Title" navItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .Plain, target: self, action: nil) navItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .Plain, target: self, action: nil) navbar.items = [navItem] view.addSubview(navbar) collectionView?.frame = CGRect(x: 0, y: height, width: UIScreen.mainScreen().bounds.width, height: (UIScreen.mainScreen().bounds.height - height))
当然,height可以是你想要的任何东西,而UIBarButton的动作是你想要的任何功能的选择器(你也根本不需要按钮)。
height
UIBarButton
编辑:
1.已调整collectionView的框架,使其不会与UINavigationBar重叠。1.将高度设为常数,以便可以在一个位置变更其所有指涉。
collectionView
UINavigationBar
flvlnr442#
Swift 4的更新答案:
private func addNavigationBar() { let height: CGFloat = 75 var statusBarHeight: CGFloat = 0 if #available(iOS 13.0, *) { statusBarHeight = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0 } else { statusBarHeight = UIApplication.shared.statusBarFrame.height } let navbar = UINavigationBar(frame: CGRect(x: 0, y: statusBarHeight, width: UIScreen.main.bounds.width, height: height)) navbar.backgroundColor = UIColor.white navbar.delegate = self as? UINavigationBarDelegate let navItem = UINavigationItem() navItem.title = "Sensor Data" navItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissViewController)) navbar.items = [navItem] view.addSubview(navbar) self.view?.frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: (UIScreen.main.bounds.height - height)) }
ct2axkht3#
这是swift 5的版本。
class ViewController: UIViewController, UINavigationBarDelegate { override func viewDidLoad() { super.viewDidLoad() view.addSubview(toolbar) toolbar.delegate = self let height: CGFloat = 75 let navbar = UINavigationBar(frame: CGRect(x: 20, y: 20, width: UIScreen.main.bounds.width, height: height)) navbar.backgroundColor = UIColor.white navbar.delegate = self let navItem = UINavigationItem() navItem.title = "Title" navItem.leftBarButtonItem = UIBarButtonItem(title: "Left Button", style: .plain, target: self, action: nil) navItem.rightBarButtonItem = UIBarButtonItem(title: "Right Button", style: .plain, target: self, action: nil) navbar.items = [navItem] view.addSubview(navbar) self.view.frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: (UIScreen.main.bounds.height - height)) } }
3条答案
按热度按时间0lvr5msh1#
请尝试将以下代码放入
viewDidLoad
:当然,
height
可以是你想要的任何东西,而UIBarButton
的动作是你想要的任何功能的选择器(你也根本不需要按钮)。编辑:
1.已调整
collectionView
的框架,使其不会与UINavigationBar
重叠。1.将高度设为常数,以便可以在一个位置变更其所有指涉。
flvlnr442#
Swift 4的更新答案:
ct2axkht3#
这是swift 5的版本。