如何在编辑时使tableViewcell选择不同或不是programming_swift3?

时间:2017-06-26 03:16:36

标签: ios swift nstableview tableviewcell

Image like this

我有一个想法是在图像中做两行红圈 默认单元格选择为无,并切换到编辑模式,默认选择 如果我在编辑模式时没有设置单元格选择,则不会显示复选标记 我不想使用故事板,我练习编程。
我试着这样做,但似乎失败了 我不知道我在哪里弄错了。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var rightBtn: UIBarButtonItem!

@IBOutlet weak var leftBtn: UIBarButtonItem!
var items:[String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A1","B1"]

var selectedIndexs = [Int]()

override func loadView() {
    super.loadView()
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    self.tableView?.allowsMultipleSelectionDuringEditing = true

    rightBtn.target = self
    leftBtn.target = self
    rightBtn.action = #selector(btnClick(_:))
    leftBtn.action = #selector(leftBtnClick(_:))
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func leftBtnClick(_ sender: AnyObject) {

    if(self.tableView!.isEditing == false) {
        self.tableView!.setEditing(true, animated:true)
    }
    else {
        self.tableView!.setEditing(false, animated:true)
    }
}

func btnClick(_ sender: AnyObject) {
    var selectedIndexs = [Int]()
    if let selectedItems = tableView!.indexPathsForSelectedRows {

        let sortedArray = selectedItems.sorted()
        print("哈:\(sortedArray)")

        for indexPath in selectedItems {
            selectedIndexs.append(indexPath.row)
        }
    }

    items.removeAt(indexes:selectedIndexs)

    self.tableView?.reloadData()
    self.tableView!.setEditing(false, animated:true)
}
}

  extension ViewController: UITableViewDelegate, UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = self.items[indexPath.row]

    if tableView.isEditing == true {
        cell.selectionStyle = .default
    }else{
        cell.selectionStyle = .none
    }

    return cell
}
}

1 个答案:

答案 0 :(得分:1)

在leftBtnClick函数中添加两行。

func leftBtnClick(_ sender: AnyObject) {
    if self.tableView!.isEditing == false {
        self.tableView!.setEditing(true, animated:true)
        self.tableView.allowsSelection = true
    } else {
        self.tableView!.setEditing(false, animated:true)
        self.tableView.allowsSelection = false
    }
}

从cellForRawAtIndexPath中删除以下代码。

if tableView.isEditing == true {
   cell.selectionStyle = .default
} else{
   cell.selectionStyle = .none
}