您的位置:首页 > 移动开发 > Swift

swift UITableViewCell插入单无格

2016-11-03 20:43 197 查看
<span style="font-family:Arial, Helvetica, sans-serif;">自学菜鸟,因为看了一文章,说是写博客可帮助成长。所以这只是记录,没有什么技术含量。如果有写错的地方,还望指正。</span>
import UIKit
class 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)
}

                                          
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: