gpt4 book ai didi

ios - '无效更新 : invalid number of items in section 0 in my collection view

转载 作者:行者123 更新时间:2023-11-28 07:34:16 24 4
gpt4 key购买 nike

当我在我的应用程序上按下 editButton 并尝试删除我的 collectionView 中的单元格时,我收到以下错误消息:

'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (3) must be equal to the number of items contained in that section before the update (3), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

看完other similar posts我仍然不确定如何应用解决方案来解决这个问题。我确实看到文件从 FileManager 中删除,因为我在 Finder 中打开了目录,但我不知道如何让 collectionView 与 FileManager 中的文件数同步。

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

var audioRecorder: AVAudioRecorder!
var audioPlayer: AVAudioPlayer!
var numberOfRecordings = 0

@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var myCollectionView: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()

recordButton.layer.cornerRadius = 10
editButton.layer.cornerRadius = 10


// Set the numberOfRecordings to be exactly the number of files stored in the File Manager so that they're in sync.
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
numberOfRecordings = fileURLs.count
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}

}

// Let's get the directory where we're going to store the recordings
func getDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}

// Let's create a genearl alert to display error messages
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}

//MARK: - Record Button Methods
@IBAction func record(_ sender: Any) {

if audioRecorder == nil {
numberOfRecordings += 1
let fileURL = getDirectory().appendingPathComponent("\(numberOfRecordings).m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]

do {
audioRecorder = try AVAudioRecorder(url: fileURL, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
recordButton.setTitle("Stop Recording", for: .normal)
} catch {
displayAlert(title: "Oops!", message: "Recording Failed")
}
} else {
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecordings, forKey: "numberOfRecordings")
recordButton.setTitle("Start Recording", for: .normal)
myCollectionView.reloadData()

}

}


//MARK: - Collection View Setup
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfRecordings
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! RecordingCollectionViewCell
cell.recordingLabel.text = String(indexPath.row + 1)
cell.layer.cornerRadius = 10
cell.delegate = self as RecordingCellDelegate
return cell
}

//MARK: - Audio Player
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let path = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")

do {
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.volume = 1.0
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print("Error: \(error.localizedDescription)")
}
}

//MARK: - Edit Button Methods
@IBAction func editButtonTapped(_ sender: Any) {
if editButton.titleLabel?.text == "Edit" {
recordButton.isEnabled = isEditing
editButton.setTitle("Stop Editing", for: .normal)
if let indexPaths = myCollectionView?.indexPathsForVisibleItems {
for indexPath in indexPaths {
if let cell = myCollectionView?.cellForItem(at: indexPath) as? RecordingCollectionViewCell {
cell.isEditing = !isEditing
}
}
}
} else {
editButton.setTitle("Edit", for: .normal)
if let indexPaths = myCollectionView?.indexPathsForVisibleItems {
for indexPath in indexPaths {
if let cell = myCollectionView?.cellForItem(at: indexPath) as? RecordingCollectionViewCell {
cell.isEditing = isEditing
}
}
}
}


}


}


extension ViewController: RecordingCellDelegate {
func delete(cell: RecordingCollectionViewCell) {
if let indexPath = myCollectionView?.indexPath(for: cell) {
// 1. Delete the recording from the File Manager
let fileManager = FileManager.default
let fileURL = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")
do {
try fileManager.removeItem(at: fileURL)

} catch let error {
print("File not found: \(error.localizedDescription)")
displayAlert(title: "Oops!", message: "File not found: \(error.localizedDescription)")
}

// 2. Delete it in the collectionView
myCollectionView.deleteItems(at: [indexPath])
}
}
}

最佳答案

您永远不会更新您的数据模型。除了删除文件并告诉 Collection View 某项已被删除外,您还需要更新 Collection View 使用的模型。这意味着您需要更新 numberOfRecordings(在调用 myCollectionView.deleteItems(at: [indexPath]) 之前)。

关于ios - '无效更新 : invalid number of items in section 0 in my collection view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673724/

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