我已经为
UISwipeActionsConfiguration
创建了一个扩展,如果您的图像大小存在问题,则可以使用该扩展。基本上,想法是从图像和文本创建一个属性字符串,并将其设置为标签,然后从该标签创建一个图像。并将其附加到
UIContextualAction
的
image
属性。
extension UISwipeActionsConfiguration {
public static func makeTitledImage(
image: UIImage?,
title: String,
textColor: UIColor = .white,
font: UIFont = .systemFont(ofSize: 14),
size: CGSize = .init(width: 50, height: 50)
) -> UIImage? {
let attachment = NSTextAttachment()
attachment.image = image
let imageString = NSAttributedString(attachment: attachment)
let text = NSAttributedString(
string: "\n\(title)",
attributes: [
.foregroundColor: textColor,
.font: font
]
)
let mergedText = NSMutableAttributedString()
mergedText.append(imageString)
mergedText.append(text)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
label.textAlignment = .center
label.numberOfLines = 2
label.attributedText = mergedText
let renderer = UIGraphicsImageRenderer(bounds: label.bounds)
let image = renderer.image { rendererContext in
label.layer.render(in: rendererContext.cgContext)
}
if let cgImage = image.cgImage {
return UIImage(cgImage: cgImage, scale: UIScreen.main.scale, orientation: .up)
}
return nil
}
}
你可以像这样使用它;
public func tableView(
_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration?
{
let deleteAction = UIContextualAction(
style: .normal,
title: nil,
handler: { [weak self] (_, _, success: (Bool) -> Void) in
success(true)
print("Your action in here")
}
)
deleteAction.image = UISwipeActionsConfiguration.makeTitledImage(
image: UIImage(named: "delete_icon"),
title: "Delete")
)
deleteAction.backgroundColor = .orange
return UISwipeActionsConfiguration(actions: [deleteAction])
}
UITableView
定义及其注释。 - Robert Dresler