【发布时间】:2018-05-08 01:45:48
【问题描述】:
我正在尝试将 UICollectionView 添加到导航栏以代替导航标题,就像在 iOS 中的本机消息应用程序中所做的那样。据我所知,这是:
let navigationBar = UINavigationBar()
var collectionview: UICollectionView!
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: navigationBar.frame.width, height: navigationBar.frame.height)
collectionview = UICollectionView(frame: navigationBar.frame, collectionViewLayout: layout)
collectionview.dataSource = self
collectionview.delegate = self
collectionview.register(UserImagesCollectionViewCell.self, forCellWithReuseIdentifier: "userCell")
collectionview.showsVerticalScrollIndicator = false
collectionview.backgroundColor = .red
let navigationItem = UINavigationItem()
navigationItem.title = ""
navigationItem.titleView = collectionview
navigationBar.items = [navigationItem]
此代码运行时没有任何错误,但在视图控制器上不显示任何内容。我在这里缺少一些东西,我不能指望它。有什么帮助吗?
编辑: 在 Mike 的回答的帮助下,这是我在导航栏中使用自定义单元格 xib 文件创建 uicollectionview 的代码。
func setupCustomCollectionView() {
if let navigationBar = self.navigationController?.navigationBar {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: navigationBar.frame.width / 4, height: navigationBar.frame.height)
collectionview = UICollectionView(frame: navigationBar.frame, collectionViewLayout: layout)
collectionview.dataSource = self
collectionview.delegate = self
let nibCell = UINib(nibName: "UserImagesCollectionViewCell", bundle: nil)
collectionview.register(nibCell, forCellWithReuseIdentifier: "userCell")
collectionview.showsVerticalScrollIndicator = false
collectionview.backgroundColor = .red
self.navigationController?.navigationBar.topItem?.titleView = collectionview
}
}
【问题讨论】:
-
您想将标题替换为“就像在 iOS 的原生消息应用中所做的那样”?请张贴这意味着什么的屏幕截图。
标签: ios swift uinavigationbar uinavigationitem