如何删除 UITableView 中变量为整数的行?

How do I delete a row in a UITableView where the var is an integer?

我正在创建一个音频录音机,每次上传后,名称都会在 table 视图(注意:常规视图)中为录音附加一个整数(例如 1、2、3 等)带有 UITableView 与 TableView Controller 的控制器)。

我在删除每一行时遇到问题,我不确定是不是因为 'numberOfRecords.remove(at: indexPath.row)' 只接受字符串。

我收到错误:"Value of type 'Int' has no member 'remove.'"

class ViewController2: UIViewController, RecordButtonDelegate, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var myTableView: UITableView!

var numberOfRecords : Int = 0

// Setting up Table View
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfRecords
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = String(indexPath.row + 1)

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let path = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: path)
        audioPlayer.play()
    }

    catch {

    }
}

// Delete rows
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete{
        numberOfRecords.remove(at: indexPath.row)

        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()

    }
}


// Audio Player
var audioPlayer : AVAudioPlayer!
var recordingSession : AVAudioSession!
var audioRecorder : AVAudioRecorder!
var recordButton: RecordButton?

@IBOutlet weak var buttonLabel2: RecordButton!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    buttonLabel2.delegate = self

}

func tapButton(isRecording: Bool) {

    // Check if we have an active recorder
    if audioRecorder == nil {
        numberOfRecords += 1
        let filename = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")

        let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                        AVSampleRateKey: 12000,
                        AVNumberOfChannelsKey: 1,
                        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]

        // Start audio recording
        do {
            audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()

        }

        catch {
            displayAlert(title: "Oops!", message: "Recording failed")
        }

        // Play speaker instead of earpiece
        let audioSession = AVAudioSession.sharedInstance()

        do {
            try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)

        } catch let error as NSError {
            print("Audio Session error: \(error.localizedDescription)")
        }


    }
    else {
        // Stop audio recording
        audioRecorder.stop()
        audioRecorder = nil

        UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
        myTableView.reloadData()

    }

}


override func viewDidLoad() {
    super.viewDidLoad()

    // Setting up Recording session
    recordingSession = AVAudioSession.sharedInstance()

    if let number : Int = UserDefaults.standard.object(forKey: "myNumber") as? Int {
        numberOfRecords = number
    }

    AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
        if hasPermission {
            print ("Accepted")
        }
    }

您遇到的问题是由于您对 Int 调用 remove(at:)。 Int 没有名为 remove(at:).

的函数

您要声明 var numberOfRecords: Int 来跟踪您的指数,然后在

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)

您正在呼叫

// this is the line that's causing your problem
numberOfRecords.remove(at: indexPath.row)

如果您想继续使用 int 来跟踪您的细胞,您应该从 numberOfRecords

中减去
numberOfRecords-=1

或者您可以使用类似这样的数组来跟踪您的记录:

// declare an array of Strings to hold your filenames
var records: [String] = []

然后在保存文件的位置将新文件名添加到表视图的数组中

// Stop audio recording
audioRecorder.stop()
audioRecorder = nil

// add your filename to your array of records for the tableview
records.append(filename)

// update your total number of records if desired
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
myTableView.reloadData()

那么你的委托函数可能看起来像这样

// Setting up Table View
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // return the total count of filenames in your array
    return records.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // set the filename in your text label
    cell.textLabel?.text = records[indexPath.row]

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // get the filename for this row
    let filename = records[indexPath.row]

    // use your filename in your path
    let path = getDirectory().appendingPathComponent("\(filename)")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: path)
        audioPlayer.play()
    }

    catch {

    }
}

并且您可以将 remove(at:) 调用更新为记录数组上的 运行

records.remove(at: indexPath.row)

编辑:

当您从记录数组中添加或删除文件名时,使用更新后的记录更新用户默认值:

// save array to user defaults when you create a new record or when you delete a record
UserDefaults.standard.setValue(records, forKey: "storedRecords")

要检索您保存的文件名数组,请从用户默认值中提取它们并使用存储的名称更新您的记录数组。

在您的 viewDidLoad 函数中替换这些行:

if let number : Int = UserDefaults.standard.object(forKey: "myNumber") as? Int {
    numberOfRecords = number
}

有了这个:

// load stored records from user defaults and verify it's what you expect to receive
if let stored = UserDefaults.standard.value(forKey: "storedRecords") as? [String] {
    // update your records array with the stored values
    records = stored
}