如何在CollectionView的UserDefaults中调用拖放后的数组索引?

发布于 2025-01-22 23:55:45 字数 3025 浏览 4 评论 0原文

我正在创建一个演示,在此中,我具有拖放功能,拖放功能正常工作,我担心的是,当我关闭应用程序并再次回到视图时,索引在数组,我想在索引上拖动时获得数组。

这是我的代码

collectionView方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
    
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
    cell.lbl.text = array[indexPath.row]
    cell.img.layer.cornerRadius = cell.img.frame.size.width / 2
    cell.lbl.layer.cornerRadius = cell.lbl.frame.size.width / 2
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: (collectionView.frame.size.width / 2) - 20, height: 200)
}

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

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

    let item = array.remove(at: sourceIndexPath.item)
    defaults.removeObject(forKey: "data")
    array.insert(item, at: destinationIndexPath.item)
    defaults.set(item, forKey: "data")
    defaults.synchronize()
    
    print(item )
}

视图确实加载了和longpressesture方法

@IBOutlet weak var collectionView: UICollectionView!
var array = ["Fateh", "Parul", "Jitendra", "Javed", "Brijesh","Pandey Ji"]
let defaults = UserDefaults.standard
var longPress : UILongPressGestureRecognizer!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    if UserDefaults.standard.array(forKey: "data") == nil {
         // userDefault has a value
   
        defaults.set(array, forKey: "data")
        
    } else  {
        let newData = defaults.object(forKey: "data")
        array = newData as! [String]
    }
    
    
    collectionView.delegate = self
    collectionView.dataSource = self
    longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
    collectionView.addGestureRecognizer(longPress)
}

@objc func handleLongGesture(gesture : UILongPressGestureRecognizer){
    switch gesture.state {
    case .began:
        guard let selectedIndex = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
            break
        }
        collectionView.beginInteractiveMovementForItem(at: selectedIndex)
    case .changed:
        collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view))
        
    case .ended:
        collectionView.endInteractiveMovement()
        defaults.synchronize()
    @unknown default:
        collectionView.cancelInteractiveMovement()
    }
}

I'm Creating an demo, In this I have Drag and Drop Functionality , Drag and Drop function is working Perfectly Fine, My Concern is , when I close the app and came back to the View again, the same is Index is showing in the array, I want to Get the array as I do Drag and Drop at a index.

Here's My Code

CollectionView Methods

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
    
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
    cell.lbl.text = array[indexPath.row]
    cell.img.layer.cornerRadius = cell.img.frame.size.width / 2
    cell.lbl.layer.cornerRadius = cell.lbl.frame.size.width / 2
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: (collectionView.frame.size.width / 2) - 20, height: 200)
}

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

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

    let item = array.remove(at: sourceIndexPath.item)
    defaults.removeObject(forKey: "data")
    array.insert(item, at: destinationIndexPath.item)
    defaults.set(item, forKey: "data")
    defaults.synchronize()
    
    print(item )
}

View Did Load and LongPressGesture Methods

@IBOutlet weak var collectionView: UICollectionView!
var array = ["Fateh", "Parul", "Jitendra", "Javed", "Brijesh","Pandey Ji"]
let defaults = UserDefaults.standard
var longPress : UILongPressGestureRecognizer!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    if UserDefaults.standard.array(forKey: "data") == nil {
         // userDefault has a value
   
        defaults.set(array, forKey: "data")
        
    } else  {
        let newData = defaults.object(forKey: "data")
        array = newData as! [String]
    }
    
    
    collectionView.delegate = self
    collectionView.dataSource = self
    longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
    collectionView.addGestureRecognizer(longPress)
}

@objc func handleLongGesture(gesture : UILongPressGestureRecognizer){
    switch gesture.state {
    case .began:
        guard let selectedIndex = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
            break
        }
        collectionView.beginInteractiveMovementForItem(at: selectedIndex)
    case .changed:
        collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view))
        
    case .ended:
        collectionView.endInteractiveMovement()
        defaults.synchronize()
    @unknown default:
        collectionView.cancelInteractiveMovement()
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆里有你的影子 2025-01-29 23:55:45

viewDidload中,如果在UserDefaults中没有保存的数据,则您正在这样做:

defaults.set(array, forKey: "data")

您将 array 设置为数据。

MoveItemat中,您正在这样做:

defaults.set(item, forKey: "data")

您仅设置一个个人 item 作为数据,当您应该设置更新的 array 时作为数据。

附带说明,不需要defaults.synchronize() ...来自苹果的 docs

同步()

等待对默认数据库和返回的任何未决异步更新;此方法是不必要的,不应使用。

In viewDidLoad, if there is no data already saved in UserDefaults, you are doing this:

defaults.set(array, forKey: "data")

You're setting the array as the data.

In moveItemAt, you're doing this:

defaults.set(item, forKey: "data")

You're setting only an individual item as the data, when you should be setting the updated array as the data.

As a side note, there is no need for defaults.synchronize() ... from Apple's docs:

synchronize()

Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文