如何删除tableview的单元格?

时间:2018-01-31 04:30:42

标签: ios swift uitableview

我的numberOfRecords是Int。 如何删除tableview中的单元格? 或者我应该改变我的方式来定义我的numberOfRecords?

我应该如何改进我的代码?

var numberOfRecords = 0

@IBAction func recordButton(_ sender: Any) {
    if audioRecorder == nil {
        numberOfRecords += 1
        let filename = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

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

            recordButton.setTitle("Stop Recording", for: .normal)
        }
        catch
        {
            displayAlert(title: "Ups!", message: "Recording failed")
        }
    }
    else
    {
        audioRecorder.stop()
        audioRecorder = nil

        UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
        myTableView.reloadData()
        recordButton.setTitle("start Recording", for: .normal)
    }

}
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{

    }
}

在调试editStyle函数里面我应该可以删除tableview里面的单元格作为编写的代码

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

2 个答案:

答案 0 :(得分:2)

试试这个:

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

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        objects.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } 
}  

答案 1 :(得分:0)

您只需在单元格上显示索引编号。如果要删除任何位置的单元格,则在重新加载tableview后,您会感觉从最后一个单元格中删除了一个单元格。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
         numberOfRecords -= 1
         tableView.reloadData()
    } 
} 

那就是它。

相关问题