2016-03-30 94 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瞭解更多詳情。