您可以使用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]
}
结果将如下所示。
另一种方法是导入具有要用作字体的图像的自定义字体,然后使用 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])
}