重新启动应用程序后,如何在集合视图中保存重新排序的单元格的位置?迅速



当我尝试使用以下两种方法对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)")
}

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

你能推荐我哪种方法?

附加信息:

"团队"数组存储类 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 中,并使用项目名称作为键。

如何存储仓位

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

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

如何收回仓位

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
}
}
}
}

我希望它有所帮助!

最新更新