美文网首页
uitableView 控制section允许编辑模式

uitableView 控制section允许编辑模式

作者: 白色天空729 | 来源:发表于2019-08-01 10:57 被阅读0次
//
//  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()
    }
}

效果图:


QQ20190801-105617.gif

核心代码:

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

相关文章

网友评论

      本文标题:uitableView 控制section允许编辑模式

      本文链接:https://www.haomeiwen.com/subject/nftqdctx.html