Swift4+Xcode9下修改UITableView滑动删除的背景色与图标报错求助
解决UITableView滑动删除自定义样式的报错与实现问题
我来帮你搞定这个问题,之前在Swift 4开发的时候也遇到过类似的报错,咱们一步步来解决:
首先解决歧义引用的报错
你碰到的Ambiguous reference to member 'tableView(_:numberOfRowsInSection:)'错误,根源是这行代码:
self.tableView.dataSource?.tableView!(self.tableView, commit: .delete, forRowAt: indexPath)
编译器没法区分你要调用的是数据源协议方法还是表格视图的代理方法,而且这种调用逻辑本身就不对——tableView(_:commit:forRowAt:)是系统用来通知你执行删除操作的回调,你不需要主动去调用它,而是应该在滑动按钮的闭包里直接处理删除数据+更新UI的逻辑。
修复后的基础自定义删除按钮代码
下面是修复报错且能自定义背景色的正确实现:
// 假设你的数据源是这个可变数组,替换成你实际的数据源 var dataArray: [String] = ["Item 1", "Item 2", "Item 3"] func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteButton = UITableViewRowAction(style: .default, title: "Delete") { [weak self] (action, indexPath) in guard let self = self else { return } // 1. 先从数据源中移除对应位置的数据 self.dataArray.remove(at: indexPath.row) // 2. 通知表格视图更新行 tableView.deleteRows(at: [indexPath], with: .automatic) } // 设置你想要的背景色,比如黑色 deleteButton.backgroundColor = .black return [deleteButton] }
这里用[weak self]是为了避免循环引用,确保内存安全。
用图标替代文字标签的实现
UITableViewRowAction没有直接的image属性,但我们有两种靠谱的实现方式:
方法一:使用字体图标(比如Font Awesome)
如果你导入了字体图标库,直接用图标对应的Unicode字符做标题,再设置样式:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // 以Font Awesome的垃圾桶图标为例,Unicode是"\u{f2ed}" let deleteIcon = "\u{f2ed}" let attributedTitle = NSAttributedString(string: deleteIcon, attributes: [ .font: UIFont(name: "FontAwesome", size: 18)!, .foregroundColor: UIColor.white ]) let deleteButton = UITableViewRowAction(style: .default, title: "") { [weak self] (action, indexPath) in guard let self = self else { return } self.dataArray.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) } deleteButton.backgroundColor = .black deleteButton.setAttributedTitle(attributedTitle, for: .normal) return [deleteButton] }
方法二:用自定义图片作为背景
如果是你自己的图标图片,可以把图片转成背景色的pattern,同时清空标题:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // 加载你的删除图标,确保图片在Assets里 guard let deleteImage = UIImage(named: "delete-icon")?.withRenderingMode(.alwaysTemplate) else { return nil } // 给图标设置白色 tint(根据你的背景色调整) let tintedImage = deleteImage.withTintColor(.white) // 把图片转成可作为背景的颜色 let imageBgColor = UIColor(patternImage: tintedImage) let deleteButton = UITableViewRowAction(style: .default, title: "") { [weak self] (action, indexPath) in guard let self = self else { return } self.dataArray.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) } deleteButton.backgroundColor = imageBgColor return [deleteButton] }
补充说明
Swift 4和Xcode 9完全支持自定义UITableViewRowAction的样式,你的实现方向是对的,只是之前的调用逻辑出了问题。只要按照上面的方式修改,就能实现自定义背景色和图标替代文字的需求啦。
内容的提问来源于stack exchange,提问作者user8893378
相关产品推荐
相关产品推荐

