当我尝试使用以下两种方法重新排序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]?
}
提前感谢您的帮助!
答案 0 :(得分:1)
我会使用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
}
}
}
}
我希望它有所帮助!