gpt4 book ai didi

Swift Collectionview 数据源和部分

转载 作者:可可西里 更新时间:2023-11-01 01:16:31 26 4
gpt4 key购买 nike

所以,我之前问过有关此问题的问题,但我认为我在这里需要更多帮助,因为我无处可去。

我的应用程序的小总结:

现在陈述:用户在一个 View Controller 上获得设备列表,并可以检查他们希望在开始屏幕上详细查看其中的哪些设备。设备的 ID 存储在一个数组中,如下所示:

devArray["device1", "device2",..].

此数组存储在 UserDefaults 中。从 URLSession 中提取服务器数据。

然后所有的东西都被拉到一起

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let colcel = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCollectionViewCell
let id = devArray[indexPath.row]
let devListItem = self.devicesFromTheServer.filter { ($0["id"] as! String) == id }[0]

设备显示在一个没有部分的 CollectionView 中,用户可以重新排列单元格。这非常有效。

我现在的意图是提供按部分对设备进行分组的功能。我想到了一本看起来像这样的字典:

dict["device1":"sectionA", "device2":"sectionA", "device3":"SectionB"]

但我不知道如何从中构建 Collectionview,而且我不确定我的字典形式是否正确...

你能帮我一下吗?

最佳答案

您可以在此处采用多种方法。第一个是二维数组,它是一个包含每个部分的设备数组的数组。另一种方法更具可扩展性,允许您仅使用设备名称对数据进行建模。

第二种方法是我在下面包含的方法。

你需要的是这样的:

/// Defines a section in data source
struct Section {

// MARK: - Properties

/// The title of the section
let title: String

/// The devices in the section
var devices: [String]
}

然后在你的 View Controller 中定义一个数组来存储如下部分:

var dataSource = [Section(title: "Section 1", devices: ["Device 1"]), Section(title: "Section 2", devices: ["Device 2","Device 3"])]

您可以使用您已有的一些逻辑,通过将设备附加到单独函数中的每个部分来自定义此设置。为了这个答案,我让它变得更简单。

然后添加这些 Collection View 数据源和委托(delegate)方法:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].devices.count
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
cell.textLabel?.text = dataSource[indexPath.section].devices[indexPath.row]
return cell
}

关于Swift Collectionview 数据源和部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com