【发布时间】:2016-06-23 23:24:52
【问题描述】:
如何将导航栏添加到未嵌入导航控制器的视图控制器(实际上是集合视图控制器)?我尝试将导航栏拖到视图上,但它没有粘住。这是在斯威夫特。
【问题讨论】:
-
我猜 Xcode 不会让你这样做,但尝试通过代码插入它,它应该可以工作。
标签: ios swift swift2 interface-builder
如何将导航栏添加到未嵌入导航控制器的视图控制器(实际上是集合视图控制器)?我尝试将导航栏拖到视图上,但它没有粘住。这是在斯威夫特。
【问题讨论】:
标签: ios swift swift2 interface-builder
尝试将此代码放入您的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 当然可以是你想要的任何东西。 UIBarButtons 的操作是您想要的任何功能的选择器。 (您也根本不需要按钮)。
编辑:
collectionView 的框架,使其不会与UINavigationBar 重叠。【讨论】:
UIViewController,将其扩展为UICollectionViewDataSource UICollectionViewDelegate,然后将collectionView 拖入其中而不是使用默认的UICollectionViewController 类和IB 对象。
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))
}
【讨论】:
这是 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))
}
}
【讨论】: