UITableViewRowAction带图像,swift

UITableViewRowAction带图像,swift,swift,uitableview,ios8,uitableviewrowaction,Swift,Uitableview,Ios8,Uitableviewrowaction,在我的应用程序中,我想使用图像而不是标题文本的UITableViewRowAction。我使用以下方法设置背景图像: let edit = UITableViewRowAction(style: .Normal, title: "Edit") { action, index in self.indexPath = indexPath self.performSegueWithIdentifier("toEdit", sender: self) } edit.backgroundColor

在我的应用程序中,我想使用图像而不是标题文本的
UITableViewRowAction
。我使用以下方法设置背景图像:

let edit = UITableViewRowAction(style: .Normal, title: "Edit") { action, index in
  self.indexPath = indexPath
  self.performSegueWithIdentifier("toEdit", sender: self)
}
edit.backgroundColor = UIColor(patternImage: UIImage(named: "edit")!)
然而,图像出现了很多次


如何修复此问题以使行中只有一个图像?

问题是用作图案的图像不适合空间,将重复该图像以填充空间。 拥有非重复图像的一个选项是

  • 使用具有固定高度的UITableViewCell
  • 使用适合该高度的图像

我编写了一个子类
UITableViewRowAction
来帮助您计算标题的长度,您只需传递rowAction和图像的大小即可

class CustomRowAction: UITableViewRowAction {

    init(size: CGSize, image: UIImage, bgColor: UIColor) {
        super.init()

        // calculate actual size & set title with spaces
        let defaultTextPadding: CGFloat = 15  
        let defaultAttributes = [ NSFontAttributeName: UIFont.systemFont(ofSize: 18)]   // system default rowAction text font
        let oneSpaceWidth = NSString(string: " ").size(attributes: defaultAttributes).width
        let titleWidth = size.width - defaultTextPadding * 2
        let numOfSpace = Int(ceil(titleWidth / oneSpaceWidth))

        let placeHolder = String(repeating: " ", count: numOfSpace)
        let newWidth = (placeHolder as NSString).size(attributes: defaultAttributes).width + defaultTextPadding * 2
        let newSize = CGSize(width: newWidth, height: size.height)

        title = placeHolder

        // set background with pattern image

        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.nativeScale)

        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor(bgColor.cgColor)
        context.fill(CGRect(origin: .zero, size: newSize))

        let originX = (newWidth - image.size.width) / 2
        let originY = (size.height - image.size.height) / 2
        image.draw(in: CGRect(x: originX, y: originY, width: image.size.width, height: image.size.height))
        let patternImage = UIGraphicsGetImageFromCurrentImageContext()!

        UIGraphicsEndImageContext()

        backgroundColor = UIColor(patternImage: patternImage)
    }
}

您可以查看我的项目:了解更多详细信息。

如果您可以使用表情符号而不是图片,请查看此项目->谢谢回复,但在我的应用程序中,我不想使用表情符号。我希望有特殊的图像,代表按钮的功能(这就是我不想使用表情符号的原因),而不是文本。你的问题解决了吗@哇,试试这个谢谢你,这似乎是我需要的你好,在我的情况下,我已经管理了高度,但我已经放置了3个按钮,现在它从宽度延伸。图像正在单元格中重复。请帮我解决这个问题。谢谢