UITableView 删除行

UITableView Delete Row

我正在制作一个 table 视图,我想制作一个功能,您可以通过向右滑动并点击删除按钮来删除一行。我和我的老师已经尝试了大约半小时来解决这个问题,但似乎没有任何效果。

 import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var StoredValues = Values()
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {//
        super.didReceiveMemoryWarning()
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "meunSegue", sender: self)

        func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            _ = segue.destination as! SecondViewController
        }
    }
    func tableView->(UITableView *)tableView canEditRowsAtIndexPath:(NSIndexPath *)indexPath {
    return YES
    }
    - (void)tableView:(UITableView *)tableView committEditStyle: (UITableViewCellEditingStyle)
    func tableView {
        var cell = UITableView.self
        var Animation = UITableViewRowAnimation(rawValue: 1)
        if editingStyle == UITableViewCellEditingStyle.delete {
            cell.deleteRows(indexPath)
            //cell.deleteRows(at: [NSIndexPath], with: UITableViewRowAnimation.automatic)

        }
    }


    class SecondViewController: UIViewController {

        var recievedData = ""
        override func viewDidLoad() {
            super.viewDidLoad()
            print(recievedData)
        }
    }
}

这是因为您的 numberOfRowsInSection 数据源实现总是 returns 1(固定)。

通常,您将对象存储在一个数组中,该数组定义了行数。并且,commitEditingStyle 应该从数组中删除对象,然后删除行。

– (void)tableView: (UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath: (NSIndexPath *)indexPath {if (editingStyle == UITableViewCellEditingStyleDelete) {
       // Delete the row from the data source
       [maTheData removeObjectAtIndex:[indexPath row]];
       // Delete row using the cool literal version of [NSArray arrayWithObject:indexPath]

       [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }
}

关注此 link 了解更多详情。

此 swift 功能可以通过向右滑动并点击删除按钮来删除一行。实际上这个函数从项目数组中删除项目然后删除行。此外,此行已从 tableView.

中删除
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        // your items include cell variables
        items.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    }
}