您可以使用UITableViewRowAction
的backgroundColor
属性来设置自定义图像或视图。关键是使用UIColor(patternImage:)
方法。
基本上,UITableViewRowAction
区域的宽度由其标题决定,因此您可以找到标题(或空格)的确切长度,并使用patternImage
方法设置图像的确切大小。
为了实现这一点,我创建了一个UIView
的扩展方法。
func image() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return UIImage()
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
制作一个带有空格并且长度精确的字符串,
fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
let kPadding: CGFloat = 20
let mutable = NSMutableString(string: "")
let attribute = [NSFontAttributeName: font]
while mutable.size(attributes: attribute).width < width - (2 * kPadding) {
mutable.append(" ")
}
return mutable as String
}
现在,您可以创建UITableViewRowAction
。
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let whitespace = whitespaceString(width: kCellActionWidth)
let deleteAction = UITableViewRowAction(style: .`default`, title: whitespace) { (action, indexPath) in
}
let kActionImageSize: CGFloat = 34
let view = UIView(frame: CGRect(x: 0, y: 0, width: kCellActionWidth, height: kCellHeight))
view.backgroundColor = UIColor.white
let imageView = UIImageView(frame: CGRect(x: (kCellActionWidth - kActionImageSize) / 2,
y: (kCellHeight - kActionImageSize) / 2,
width: 34,
height: 34))
imageView.image = UIImage(named: "x")
view.addSubview(imageView)
let image = view.image()
deleteAction.backgroundColor = UIColor(patternImage: image)
return [deleteAction]
}
结果将会看起来像这样。
![输入图像描述](https://istack.dev59.com/kPsLe.gif)
另一种方法是导入拥有所需图片的自定义字体,并使用UIButton.appearance
。然而,这将影响其他按钮,除非您手动设置其他按钮的字体。
从iOS 11开始,它将显示此消息[TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.
。目前仍在工作,但在未来更新中将不再工作。
==========================================
对于iOS 11及以上版本,您可以使用:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
completion(true)
}
let muteAction = UIContextualAction(style: .normal, title: "Mute") { (action, view, completion) in
completion(true)
}
deleteAction.image = UIImage(named: "icon.png")
deleteAction.backgroundColor = UIColor.red
return UISwipeActionsConfiguration(actions: [deleteAction, muteAction])
}