//
// ViewController.swift
// UItableViewEditDemo
//
// Created by 郑东喜 on 2019/8/1.
// Copyright © 2019 郑东喜. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var dataSource = [["a","asd","cc"],
["a2","asd2","cc2"]]
lazy var tableVie: UITableView = {
let d = UITableView(frame: UIScreen.main.bounds, style: .grouped)
d.delegate = self
d.dataSource = self
d.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
return d
}()
lazy var rightItem: UIBarButtonItem = {
let d = UIBarButtonItem(title: "编辑", style: .done, target: self, action: #selector(setTableEditable(_:)))
return d
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addSubview(tableVie)
self.navigationItem.rightBarButtonItem = rightItem
}
@objc func setTableEditable(_ sender : UIBarButtonItem) {
self.tableVie.setEditing(true, animated: true)
}
}
extension ViewController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource[section].count
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return false
} else {
return true
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return UITableViewCell.EditingStyle(rawValue: UITableViewCell.EditingStyle.delete.rawValue | UITableViewCell.EditingStyle.insert.rawValue)!
}
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
cell?.textLabel?.text = self.dataSource[indexPath.section][indexPath.row]
return cell ?? UITableViewCell()
}
}
效果图:

核心代码:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return false
} else {
return true
}
}
表示控制是否允许进行编辑
网友评论