【发布时间】:2016-03-14 22:44:27
【问题描述】:
我想为表格视图编辑模式中出现的汉堡包图标使用自定义颜色,甚至最好使用自定义图像。我在最初位于 Objective-C 的旧线程中发现了这个 Swift 代码 sn-p(可在此处找到: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)
}
【问题讨论】:
-
在设置编辑之前,您是否在 TVC 中设置了正确的
accessoryType? -
另外,如果您有问题,即使是关于旧答案的问题,写一个新问题更合适,因为答案应该是答案,而不是对新解决方案的查询。
-
感谢您的帮助,sschale!我以编程方式设置了我的自定义单元格(尽管它们与普通单元格没有太大区别),但我还没有分配附件类型。那应该是哪一个?附带说明一下,汉堡包图标确实出现了,但不知何故,该代码找不到它们的子视图。
-
好吧,如果他们出现了,那么您无需担心。我要做的是在
for view in subviews、print(view.dynamicType.description())里面看看你有什么。 -
该死,我没想到。我已经尝试并打印了很多,结果 reorderControl 是单元格的子视图(不应该被原始代码找到吗?)。我可以通过在 visibleCells 中查找来更改它。虽然有一个错误,请看看我上面更新的帖子!
标签: ios swift uitableview editing