Working with images in tableView:editActionsForRow

2019-08-18 05:09发布

问题:

Here is some trouble I am having working with a UITableView, more precisely using an image in tableView:editActionsForRowAt:

Below follows my relevant code. It may be useful to say that the images I am using here are all square 70x70.

func tableView(_ tableView: UITableView,
               editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    var patternImg:UIImage?

    let upBtn = UITableViewRowAction(style: .normal, title: "") {
        action, index in
        print("upBtn button tapped")
    }
    patternImg = self.swipeCellImage(named: "UpIcn", side: 46.0)
    upBtn.backgroundColor = UIColor(patternImage: patternImg!)

    let downBtn = UITableViewRowAction(style: .normal, title: "") {
        action, index in
        print("downBtn button tapped")
    }
    patternImg = swipeCellImage(named: "DownIcn", side: 46.0)
    downBtn.backgroundColor = UIColor(patternImage: patternImg!)

    let rmvBtn = UITableViewRowAction(style: .destructive, title: "") {
        action, index in
        print("rmvBtn button tapped")
    }
    patternImg = swipeCellImage(named: "TrashIcn", side: 46.0)
    rmvBtn.backgroundColor = UIColor(patternImage: patternImg!)

    return [downBtn,upBtn,rmvBtn]
}


func swipeCellImage(named name: String, side: CGFloat) -> UIImage? {
    let theImage = UIImage(named: name)
    UIGraphicsBeginImageContextWithOptions(CGSize(width: side*2, height: side), false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(UIColor.clear.cgColor)
    theImage?.draw(in: CGRect(x: 0, y: 0, width: side, height: side))
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return resultImage
}

Things work, but unfortunately only up to a certain point. Looking at this screen shot shows that there is an unwanted repetion of the images. Clearly I want each button(Icon) to only appear one time each.

Can anyone see how I need to fix my code to avoid this repetion?

回答1:

To avoid that, you have to increase width size asper your requirement.

    UIGraphicsBeginImageContextWithOptions(CGSize(width:      self.view.frame.width, height: commonHei), false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()

    context!.setFillColor(textColor.cgColor) // CHECK BY CHANGE BGCOLOR
    context!.fill(CGRect(x: 0, y: 0, width: (self.view.frame.width) / 3, height: commonHei)) // INCREASE WIDTH SIZE
    var img: UIImage = UIImage(named: "pause")!
    img.draw(in: CGRect(x: 0, y: 0, width: 30, height: 30)) // Change position as per ur requirement.
    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

If you having more doubt, then check on the 3D view.