在表格视图编辑模式

时间:2016-03-14 22:44:28

标签: ios swift uitableview editing

我想为表视图编辑模式中出现的汉堡包图标使用自定义颜色,最好甚至使用自定义图像。我在一个较旧的主题中找到了这个Swift代码片段,最初是在Objective-C中(在这里找到:Change default icon for moving cells in UITableView):

override func setEditing(editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if editing {
        for view in subviews as [UIView] {
            if view.dynamicType.description().rangeOfString("Reorder") != nil {
                for subview in view.subviews as [UIImageView] {
                    if subview.isKindOfClass(UIImageView) {
                        subview.image = UIImage(named: "yourimage.png")
                    }
                }
            }
        }
    }
}

为了适应我的TableViewController,我已经将开始循环的行更改为: for view in tableView.subviews as [UIView] {似乎有用,但找不到带有“重新排序”描述​​的视图。从那以后这个改变了吗?

我会在旧帖子中问过,但由于声誉我还不被允许。

非常欢迎任何见解!

编辑:我可以通过将上面的代码更改为:

来更改图像
override func setEditing(editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if editing {
      for cell in tableView.visibleCells {
        for view in cell.subviews {
          if view.dynamicType.description().rangeOfString("Reorder") != nil {
            for subview in view.subviews as! [UIImageView] {
              if subview.isKindOfClass(UIImageView) {
                subview.image = UIImage(named: "yourimage.png")
                //subview.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
              }
            }
          }
        }
      }
   }
}

但是,有一个错误,当向下滚动时并非所有图标都会被更改。一些单元格仍然会有原始图标。我想这与重复使用的细胞有关。这有什么解决方案吗?

编辑2 :我通过确保在cellForRowAtIndexPath方法中执行相同的图像替换逻辑来解决上述问题。此外,我正在检查图像是否已经更改,因为如果之前有图像,图像会有奇怪的偏移。

override func setEditing(editing: Bool, animated: Bool) {
  super.setEditing(editing, animated: animated)

  if editing {
    for cell in tableView.visibleCells {
      setEditingAccessoryView(forCell: cell)
    }
  }
}

func setEditingAccessoryView(forCell cell: UITableViewCell) {
  for view in cell.subviews {
    if view.dynamicType.description().rangeOfString("Reorder") != nil {
      for subview in view.subviews as! [UIImageView] {
        if subview.isKindOfClass(UIImageView) {
          if subview.image != UIImage(named: "yourImage.png") {
            subview.image = UIImage(named: "yourImage.png")
            //subview.frame = CGRect(x: 20, y: 20, width: 20, height: 20)
          }
        }
      }
    }
  }
}

在cellForRowAtIndexPath中:

if editing {
  setEditingAccessoryView(forCell: cell)
}

1 个答案:

答案 0 :(得分:1)

很高兴我们将您的问题排序。对于您的最后一期,我建议您在cellForRowAtIndexPath:中明确调用替换逻辑,以便在每次显示单元格时强制调用代码。

(顺便说一下,记录总是一个很好的方法来解决一个令人费解的问题,)

相关问题