【问题标题】:how to select Table View row selection with custom checkbox button?如何使用自定义复选框按钮选择表格视图行选择?
【发布时间】:2017-11-15 06:01:30
【问题描述】:

如何使用自定义按钮选择 tableview 行。我有另一个按钮,称为选择所有它在表格视图之外我的问题是在点击表格视图按钮外部时如何在表格视图行内选择和取消选择?同时我可以在表格视图中选择单行吗?如何在swift 3中做到这一点?这是我在 cellforrow 方法中的代码

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let identifier = "Custom"
    var cell: TStudentAttendanceCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    if cell == nil {
        tableView.register(UINib(nibName: "TStudentAttendanceCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TStudentAttendanceCell
    }
    print("studentAttendanvceArray--",studentAttendanceArray.object(at: indexPath.row) )
    var localDic :NSDictionary!

    localDic = studentAttendanceArray.object(at: indexPath.row) as! NSDictionary

    Common.sharedInstance.StopActivity()        
    cell.profile_img.image = self.image
    cell.name_lbl.text = localDic["student_name"] as? String
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 90))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell

}

【问题讨论】:

  • 你的问题不清楚提供相关代码
  • 我已经看过该代码,但这里我的所有按钮都在 tableview 之外。
  • @kishan 我在 cellforrow 方法中没有看到任何按钮。你有吗?
  • @rajesh 我没有写任何东西我没有得到任何东西怎么做那为什么。

标签: ios swift uitableview


【解决方案1】:

视图控制器

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

  @IBOutlet var tableView: UITableView!
  var allStudentsArr:[[String:String]] = []
  var selectedRows:[IndexPath] = []


  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.allowsSelection = false
    allStudentsArr = [["name":"name1"],["name":"name2"],["name":"name3"],["name":"name4"],["name":"name5"],["name":"name6"],["name":"name7"],["name":"name8"]]
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allStudentsArr.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
    cell.nameLbl.text = allStudentsArr[indexPath.row]["name"]
    if selectedRows.contains(indexPath)
    {
      cell.checkBox.setImage(UIImage(named:"selected"), for: .normal)
    }
    else
    {
      cell.checkBox.setImage(UIImage(named:"unselected"), for: .normal)
    }
    cell.checkBox.tag = indexPath.row
    cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
    return cell
  }
  @objc func checkBoxSelection(_ sender:UIButton)
  {
    let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
    if self.selectedRows.contains(selectedIndexPath)
    {
      self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
    }
    else
    {
      self.selectedRows.append(selectedIndexPath)
    }
    self.tableView.reloadData()
  }
  @IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
    self.selectedRows = getAllIndexPaths()
    self.tableView.reloadData()
  }

  func getAllIndexPaths() -> [IndexPath] {
    var indexPaths: [IndexPath] = []
      for j in 0..<tableView.numberOfRows(inSection: 0) {
        indexPaths.append(IndexPath(row: j, section: 0))
      }
        return indexPaths
  }
}

自定义单元格

class CustomTableViewCell: UITableViewCell {

  @IBOutlet var nameLbl: UILabel!
  @IBOutlet var checkBox: UIButton!
}

【讨论】:

  • 我用过这个,它工作正常..我对这个选择有疑问,在我的情况下需要获取选定单元格的数据但我收到最后一个对象的数据,但每个对象的索引会有所不同objects。你能帮我得到那个值吗。
  • 是的,我需要为此找出解决方案,如果你能帮助我。
  • 你能解释一下你的问题吗?
  • 问题是选定单元格的数据将被重复...例如:考虑 [1,2,3,4,5,6,7,8,9,10] 在此数组中您选择的 2 ,4,8,9 和所选对象的索引 (1,3,7,8) 仅返回正确..但单元格的数据返回像 (9,9,9,9) 最后一个对象,计数将是选定对象的数量。这是我面临的问题。
  • "但是单元格的数据返回像 (9,9,9,9)" 你如何获取单元格的数据?
【解决方案2】:

这就是您如何以编程方式选择单个部分的所有行

@IBAction func didTapSelectAllButton(sender: UIButton) {
        let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
        for row in 0..<totalRows {
            let indexPath = IndexPath(row: row, section: 0)
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }

如果您不想使用 tableView 的默认复选框,请禁用 tableView 的 multipleSelection 并使用额外的全局数组实现逻辑。

var selectedArrayIndex = [Int]()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
    }else {
        selectedArrayIndex.append(indexPath.row)
    }
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if selectedArrayIndex.contains(indexPath.row) {
        // Enable You Check
        cell.checkBoxView.isHidden = false
    }else {
        cell.checkBoxView.isHidden = true
    }
}
@IBAction func didTapSelectAllButton(sender: UIButton) {
    let totalRows = tableView.numberOfRows(inSection: 0)// Make some logic if you have more than 1 section
    selectedArrayIndex.removeAll()
    for row in 0..<totalRows {
        selectedArrayIndex.append(row)
    }
}

【讨论】:

  • 实际上我已经将 xib 文件用于 tableview 单元格。因为我已经选择了一个按钮作为复选标记。因此,当我单击所有按钮或单击单行状态时,应该更改。和按钮图像也应更改为选中状态。
  • 您需要另一个数组来添加您选择的数据。并在您取消选择它们时将其删除。然后在 cellForRow 方法中,您将检查此索引处的数据是否存在于所选数组中,如果是,则标记选择否则未选中。
  • 你能提供示例代码吗?我不清楚你的解决方案@Syed Qamar。
  • @kishan 立即查看。
  • 我使用了这段代码,但遇到了一个问题,我必须将所选内容发送到 API,最后一个索引对象将为空。为什么会这样?
猜你喜欢
  • 2019-02-16
  • 2016-06-24
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2021-01-27
相关资源
最近更新 更多