gpt4 book ai didi

ios - 重新启动应用程序后,如何在 Collection View 中保存重新排序的单元格的位置? swift

转载 作者:行者123 更新时间:2023-11-28 15:23:25 25 4
gpt4 key购买 nike

当我尝试使用这两种方法对 UICollectionView 中的单元格位置重新排序时:

var teams: [Team]?

override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}

override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

if let temp = teams?[sourceIndexPath.item] {
teams?[sourceIndexPath.item] = (teams?[destinationIndexPath.item])!
teams?[destinationIndexPath.item] = temp
}

print("Starting Index: \(sourceIndexPath.item)")
print("Ending Index: \(destinationIndexPath.item)")
}

它工作正常但是在重新启动我的应用程序后我想保存重新排序的单元格的位置。

您可以推荐我哪种方法?

附加信息:

“teams”数组存储类 Team 的对象:

class Team: NSObject {

var id: String?
var name: String?
var logo: String?
var players: [Player]?
}

class Player: NSObject {

var alias: String?
var name: String?
var age: String?
var country: String?
var imageName: String?
var info: Info?
}

class Info: NSObject {

var screenshots: [String]?
var bio: String?
var gear: Gear?
var povs: [String]?
var cfg: Config?
}

class Gear: NSObject {

var monitor: String?
var mouse: String?
var mousepad: String?
var keyboard: String?
var headset: String?
}

class Config: NSObject {

var mouseSettings: [String]?
var monitorSettings: [String]?
var crosshaircfg: [String]?
}

预先感谢您的帮助!

最佳答案

为此我会使用 UserDefaults。

我将位置作为整数存储在 userDefaults 中,并使用项目名称作为键。

How to store the positions

func saveReorderedArray() {
for (index, item) in yourArray.enumerated() {
let position = index + 1
UserDefaults.standard.set(position, forKey: item.name)
}
}

在应用程序启动时,我调用了 reorderArray 函数来获取位置并将其存储在使用项目名称作为键的字典数组中。

How to retreive the positions

func reorderArray() {
var items: [[String: Int]] = []

// Get the positions
for item in yourArray {
var position = UserDefaults.standard.integer(forKey: item.name)

// If a new item is added, set position to 999
if position == 0 {
position = 999
}

items.append([itemName : position])
}

for item in items {
// Get position from dictionary
let position = Array(item.values)[0]
let itemName = Array(item.keys)[0]

// Get index from yourArray
let index = yourArray.index { (item) -> Bool in
item.name == itemName
}

// Arrange the correct positions for the cells
if let i = index {
let m = yourArray.remove(at: i)

// Append to last position of the array
if position == 999 {
yourArray.append(m)
}
else {
yourArray.insert(m, at: position - 1) // Insert at the specific position
}
}
}
}

希望对您有所帮助!

关于ios - 重新启动应用程序后,如何在 Collection View 中保存重新排序的单元格的位置? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45602377/

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