Ale*_*ter 2 uinavigationbar uinavigationitem ios swift
我正在尝试将 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]
Run Code Online (Sandbox Code Playgroud)
此代码运行时没有任何错误,但在视图控制器上不显示任何内容。我在这里缺少一些东西,但我无法指出它。有什么帮助吗?
编辑:在 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
}
}
Run Code Online (Sandbox Code Playgroud)
我能够使用以下命令显示集合视图:
self.navigationController?.navigationBar.topItem?.titleView = collectionview
Run Code Online (Sandbox Code Playgroud)
...而不是创建导航项的最后四行代码。
我注意到,由于layout.itemSize被设置为占据整个导航栏,因此cellForItemAt即使我在 中指定了更大的数字,该方法也仅被调用一次numberOfItemsInSection。
通过将 更改layout.itemSize为更小的值,cellForItemAt被多次调用。
| 归档时间: |
|
| 查看次数: |
1270 次 |
| 最近记录: |