首页 > 解决方案 > UITableViewCell 3 Time Selected 在多选时更改背景颜色

问题描述

我有 5 行。选择 3 个或更多时,背景颜色会发生变化。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    let backgroundView = UIView()
    backgroundView.backgroundColor = YOUR_COLOR_HERE
    cell.selectedBackgroundView = backgroundView
    return cell
}

这些代码改变了免费的颜色。但是我希望在选择 3 个或更多时改变背景颜色。

我怎样才能做到这一点?

标签: iosswiftuitableviewselected

解决方案


首先,您应该为这两种状态添加配置,无论 tableviewCell 是否满足isTapsEnough条件。

var numberOfTaps: Int = 0

var isTapsEnough: Bool { retrun numberOfTaps >= 3  }

func tap() {
  self.numberOfTaps += 1
  if self.isTapsEnough { 
    self.tableView.reloadData()
  }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
  cell.contentView.backgroundColor = self.isTapsEnough ? .yellow : .clear
  return cell
}

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

  self.tap()
}

推荐阅读