My option is trying to use the UImageView contentMode behavior, and when that was not enough, I found a good use for a pair of Core Geometry Rect methods, since they hold the target frame in the center of the cell frame. Using a vision check, it seems that swiping removed half of my normal cell width, so where the magic numbers appear.
Swift 3.0
extension UITableViewRowAction { func setIcon(iconImage: UIImage, backColor: UIColor, cellHeight: CGFloat, cellWidth:CGFloat) ///, iconSizePercentage: CGFloat) { let cellFrame = CGRect(origin: .zero, size: CGSize(width: cellWidth*0.5, height: cellHeight)) let imageFrame = CGRect(x:0, y:0,width:iconImage.size.width, height: iconImage.size.height) let insetFrame = cellFrame.insetBy(dx: ((cellFrame.size.width - imageFrame.size.width) / 2), dy: ((cellFrame.size.height - imageFrame.size.height) / 2)) let targetFrame = insetFrame.offsetBy(dx: -(insetFrame.width / 2.0), dy: 0.0) let imageView = UIImageView(frame: imageFrame) imageView.image = iconImage imageView.contentMode = .left guard let resizedImage = imageView.image else { return } UIGraphicsBeginImageContextWithOptions(CGSize(width: cellWidth, height: cellHeight), false, 0) guard let context = UIGraphicsGetCurrentContext() else { return } backColor.setFill() context.fill(CGRect(x:0, y:0, width:cellWidth, height:cellHeight)) resizedImage.draw(in: CGRect(x:(targetFrame.origin.x / 2), y: targetFrame.origin.y, width:targetFrame.width, height:targetFrame.height)) guard let actionImage = UIGraphicsGetImageFromCurrentImageContext() else { return } UIGraphicsEndImageContext() self.backgroundColor = UIColor.init(patternImage: actionImage) } }
Usage: from the editActions ... method of a tableview delegate.
let cellHeight = (self.tableView(tableView, cellForRowAt: indexPath)).frame.size.height let cellWidth = (self.tableView(tableView, cellForRowAt: indexPath)).frame.size.width let favorite = UITableViewRowAction(style: .normal, title: nil) { action, index in //perform action debugPrint("Test") } favorite.setIcon(iconImage:
Tommie C. Dec 12 '18 at 5:13 2018-12-12 05:13
source share