UITableViewRowAction image for title

后端 未结 8 1810
情歌与酒
情歌与酒 2020-12-02 15:44

I made a custom UITableViewRowAction. Now I\'d like to add an image instead of the text. I know that it\'s possible but don\'t know how to do it. Does someone of you knows

8条回答
  •  自闭症患者
    2020-12-02 16:13

    My variation tries to use UImageView's contentMode behavior and when that was not enough, I found some good use for a couple of the Core Geometry Rect methods because they keep the target frame centered within the cell frame. Using an eye test, It appears that swiping was removing half of my normal cell width so that's where the magic numbers show up.

    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 the 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: #imageLiteral(resourceName: "favorite"), backColor: .green, cellHeight: cellHeight, cellWidth:cellWidth)
    

提交回复
热议问题