我终于可以在集合视图中成功地对单元格进行重新排序,但是在重新排序之后,尽管有UserDefaults并且在重新启动应用程序后看到处于重新排序状态的集合视图,我无法保存。
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if collectionView == 1configcollectionview {
let itemToMove = keystring[sourceIndexPath.row]
keystring.remove(at: sourceIndexPath.row)
keystring.insert(itemToMove, at: destinationIndexPath.row)
print("Starting Index: \(sourceIndexPath.row)")
print("Ending Index: \(destinationIndexPath.row)")
UserDefaults.standard.set(keystring, forKey:"keystringreorder")
// let movekey = keystring.remove(at: sourceIndexPath.item)
// keystring.insert(movekey, at: destinationIndexPath.item)
}
if collectionView == 2configcollectionview {
let movekey1 = keystring1.remove(at: sourceIndexPath.item)
keystring1.insert(movekey1, at: destinationIndexPath.item)
print("Starting Index: \(sourceIndexPath.item)")
print("Ending Index: \(destinationIndexPath.item)")
UserDefaults.standard.set(keystring1, forKey:"keystringreorder1")
}
if collectionView == 3configcollectionview {
let movekey2 = keystring2.remove(at: sourceIndexPath.item)
keystring2.insert(movekey2, at: destinationIndexPath.item)
print("Starting Index: \(sourceIndexPath.item)")
print("Ending Index: \(destinationIndexPath.item)")
UserDefaults.standard.set(keystring2, forKey:"keystringreorder2")
}
}
override func viewDidLoad() {
super.viewDidLoad()
let orderkeystring = UserDefaults.standard.object(forKey:"keystringreorder")
if(orderkeystring != nil) {
keystring = orderkeystring as! [String]
}
}
我相信你必须使用reloadData()
方法重新加载collectionView数据
let orderkeystring = UserDefaults.standard.object(forKey:"keystringreorder")
if(orderkeystring != nil) {
keystring = orderkeystring as! [String]
// Don't forget to reload data here
1configcollectionview,reloadData()
}