2016-03-30 93 views
2

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

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")!) 

但是图像出现很多次。

enter image description here

我怎样才能解决这个问题,以只有一个图像行?

+0

请检查这一个,如果你可以使用emojis而不是图像 - > http://stackoverflow.com/a/32735211/767329 –

+0

感谢您的答复,但在我的应用程序,我不想使用emojis。我想要有特殊的图像,代表按钮的功能(这是我不想使用表情符号的原因),而不是文字。 –

+0

你的问题解决了吗? @ Vah.Sah –

回答

1

问题是用作图案的图像不适合空间,它将被重复以填充它。 一个选择具有非重复的图像是

  • 使用一个UITableViewCell具有固定高度
  • 适合身高
0

我已经写了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) 
    } 
} 

您可以看到我的项目:CustomSwipeCell了解更多详情。