我试图把导航栏中的集合视图,如在iMessage组聊天中看到的,所有成员都在导航栏中的圆圈中有他们的首字母缩写。如何把iMessage群组聊天中的导航栏中的集合视图
我在SO上发现了一个答案here,我尽了最大努力将它转换为iOS10/Swift 3,但收集视图单元格没有正确显示在导航栏中。这里是我的代码:
import UIKit
weak var collectionView: UICollectionView?
class ChatController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(80)), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.clear
navigationItem.titleView? = collectionView
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.delegate? = self
collectionView.dataSource? = self
view.addSubview(collectionView)
collectionView.reloadData()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath))
cell.backgroundColor = UIColor.orange
cell.layer.cornerRadius = 24
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: CGFloat(50), height: CGFloat(50))
}
}
和导航栏类:
import Foundation
import UIKit
class NavigationBar: UINavigationBar {
var chatController: ChatController?
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: CGFloat(self.superview!.bounds.size.width), height: CGFloat(80))
}
func setFrame(frame: CGRect) {
var f = frame
f.size.height = 80
super.frame = f
}
}
它看起来像集合视图细胞被显示出来,但他们的导航栏,而不是在它里面下方(见下文图片)。如果我隐藏导航栏,单元格将转到视图的顶部,但我希望在导航栏中包含它们。
下面是在应用程序委托我的UI代码,不知道我在做一个新手的错误在这里:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: ChatController())
return true
}
我这样做编程方式(没有故事板)。任何人都可以看到我要去哪里吗?
调用'view.addSubview(collectionView)collectionView.reloadData()'作为'viewDidLoad'中最后一次调用。将代码发布到添加导航条的地方。 – shallowThought
谢谢,我忘了添加子视图..不幸的是,它并没有解决它!仍然只是一个普通的视图控制器/导航栏。 – KingTim
显示如何添加ChatController。 – shallowThought