iOS 14 中的新功能,您可以使用UICollectionViewCompositionalLayout.list
NSDiffableDataSourceSectionSnapshot 来制作自动大纲类型的列表。Apple 在 WWDC 视频中演示了这一点,他们有一个名为 Modern Collection Views 的示例代码项目也显示了这一点。
但是当我这样做时,它不起作用。我看到了根项目,但是当我点击它时,它并没有展开。为什么不?
即使我将 Apple 的代码复制并粘贴到我自己的项目中,我也遇到了这个问题。我不明白。同样的代码适用于 Apple 的项目,但不适用于我的项目。
这是一个完整的可重现示例。这是项目的全部代码。告诉我它有什么问题!
应用代理
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
场景代表
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let scene = scene as! UIWindowScene
self.window = UIWindow(windowScene: scene)
self.window!.rootViewController = CollectionViewController()
self.window!.makeKeyAndVisible()
}
}
视图控制器
import UIKit
class CollectionViewController: UICollectionViewController {
init() {
let config = UICollectionLayoutListConfiguration(appearance: .plain)
let layout = UICollectionViewCompositionalLayout.list(using: config)
super.init(collectionViewLayout: layout)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private let cellId = "Cell"
var dataSource: UICollectionViewDiffableDataSource<String, String>! = nil
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(UICollectionViewListCell.self, forCellWithReuseIdentifier: self.cellId)
let ds = UICollectionViewDiffableDataSource<String, String>(collectionView:self.collectionView) { cv, ip, s in
let cell = cv.dequeueReusableCell(withReuseIdentifier: self.cellId, for: ip) as! UICollectionViewListCell
var contentConfig = cell.defaultContentConfiguration()
contentConfig.text = s
if ip.item == 0 {
let opts = UICellAccessory.OutlineDisclosureOptions(style: .header)
cell.accessories = [.outlineDisclosure(options: opts)]
} else {
cell.accessories = []
}
cell.contentConfiguration = contentConfig
return cell
}
self.dataSource = ds
var snap = NSDiffableDataSourceSectionSnapshot<String>()
snap.append(["Pep"], to: nil)
snap.append(["Manny", "Moe", "Jack"], to: "Pep")
self.dataSource.apply(snap, to: "Dummy", animatingDifferences: false, completion: nil)
}
}