【问题标题】:How to make only two cells of UITableview selectable at a time in swift如何在swift中一次只选择两个UITableview单元格
【发布时间】:2017-07-18 10:51:39
【问题描述】:

是否可以一次只选择 UITableview 的两个单元格?目前我只能设置 UITableView 的单选或多选。

请任何人都可以为此在 Swift3 中发布想法或代码?

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
    let currentItem = data[indexPath.row]
    if currentItem.selected {
      cell.imageView!.image = UIImage(named:"check")!
      cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
    } else {
      cell.imageView!.image = nil
      cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
    }

    return cell
  }

【问题讨论】:

    标签: ios uitableview swift3 xcode8


    【解决方案1】:

    在选择单元格时,您将在@ 987654321中获取回调。因此,您可以跟踪选定的单元格并相应地取消选择单元格。使用数组来跟踪所有选定的单元格

    var selectedIndexes = [Int]()
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            if (selectedIndexes.contains(indexPath.row)) {
               selectedIndexes.remove(at: selectedIndexes.index(of: indexPath.row)!)
            } else {
                if selectedIndexes.count == 2 {
                    selectedIndexes[0] = indexPath.row
                } else {
                    selectedIndexes.append(indexPath.row)
                }
    
            }
            tableView.reloadData()
    }
    
       override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
        let currentItem = data[indexPath.row]
        if selectedIndexes.contains(indexPath.row) {
          cell.imageView!.image = UIImage(named:"check")!
          cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
        } else {
          cell.imageView!.image = nil
          cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
        }
    
        return cell
      }
    

    【讨论】:

    • 怎么做??
    • 它显示“Type int has no member contains”错误
    • 很抱歉,将 selectedIndexes 声明为 var selectedIndexes = [Int]() 时出错
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2015-05-31
    相关资源
    最近更新 更多