swift UITableViewCell插入单无格

来源:互联网 发布:足迹软件下载 编辑:程序博客网 时间:2024/05/16 06:57
<span style="font-family:Arial, Helvetica, sans-serif;">自学菜鸟,因为看了一文章,说是写博客可帮助成长。所以这只是记录,没有什么技术含量。如果有写错的地方,还望指正。</span>
import UIKitclass ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {    var months = ["january", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]    var tableView = UITableView()        override func viewDidLoad() {        super.viewDidLoad()        self.title = "tableView"                tableView = UITableView(frame: view.bounds, style: UITableViewStyle.plain)        tableView.delegate = self        tableView.dataSource = self                //默认状态下,开启表格的编辑模式        tableView.setEditing(true, animated: false)        //注册cell        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "month")        self.view.addSubview(tableView)    }    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return months.count    }        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let ID = "month"        var cell = tableView.dequeueReusableCell(withIdentifier: ID)        if cell == nil {            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: ID)        }        cell!.textLabel!.text = months[indexPath.row]        return cell!    }        //添加一个代理方法,用来设置单元格的编辑模式为插入模式    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {        return UITableViewCellEditingStyle.insert    }        //响应单元格的插入事件    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {        //判断如果编辑模式为插入,则执行之后的代码        if editingStyle == .insert {            //获取插入位置的单元格,在段落中的行数            let rowNum = indexPath.row            //往数组中同步插入新数据,及时更新数据源            months.insert("moon", at: rowNum)                        //创建一个包含待插入单元格位置信息的新数组            let indexPaths = [indexPath]            //往表格视图中的指定位置,插入新的单元格            tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.right)        }    }        override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}




tableView.setEditing(true, animated: false) 代码决定了 TabelViewcell 前面的状态“+”。若想去前面除“+”号,

可先设置左侧编辑按扭为系统自带的专门实现编辑功能的按扭:

self.navigationItem.leftBarButtonItem = =self.editButtonItem
重写setEditing方法:

  //当点击系统处自带的编辑按扭时,调用此方法    //参数 editing 为是否编辑    //参数 animated 为是否显示动画    override func setEditing(_ editing: Bool, animated: Bool) {        super.setEditing(editing, animated: animated)                tableView.setEditing(editing, animated: animated)        tableView.setEditing(true, animated: true)    }


                                          




0 0