【问题标题】:Trying to set a button with an image in tableView:editActionsForRowAt:尝试在 tableView:editActionsForRowAt 中设置带有图像的按钮:
【发布时间】:2018-01-28 04:04:54
【问题描述】:

使用 Xcode 9.2,在 UITableView 中,当单元格被左滑时,我正在设置一个带有图像但没有文本的按钮。 这是我正在使用的精确代码:

func tableView(_ tableView: UITableView,
               editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let myButton = UITableViewRowAction(style: .normal, title: "") {
        action, index in
        print("myButton was tapped")
    }
    myButton.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)

    return [myButton]
}

它可以工作,但图像出现在单元格的底部。

我怎样才能把它带到中心?

以防万一,这是我用于测试的图像(70x70 像素):

这是它在表格视图中的外观:

【问题讨论】:

  • 这很奇怪,它确实以我为中心。您能否上传一张图片并展示它的外观以及您的图片使用哪种尺寸?
  • 我刚刚编辑了帖子以包含我正在使用的测试图像。

标签: ios swift uitableview uitableviewrowaction


【解决方案1】:

这是其中一种方式。您必须使用UIGraphicsBeginImageContextWithOptions 创建图像。

func swipeCellButtons() -> UIImage 
 {
     let commonWid : CGFloat = 40
     let commonHei : CGFloat = 70 // EACH ROW HEIGHT

     var img: UIImage = UIImage(named: "pause") // TRY IMAGE COLOR WHITE

     UIGraphicsBeginImageContextWithOptions(CGSize(width: commonWid, height: commonHei), false, UIScreen.main.scale)
     let context = UIGraphicsGetCurrentContext()
     context!.setFillColor(UIColor.clear.cgColor)
     context!.fill(CGRect(x: 0, y: 0, width: commonWid, height: commonHei))
     var img: UIImage = UIImage(named: "pause")!
     img.draw(in: CGRect(x: 5, y: 15, width: 30, height: 30))
     let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
     UIGraphicsEndImageContext()

     return newImage
 }


func tableView(_ tableView: UITableView,
               editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let myButton = UITableViewRowAction(style: .normal, title: "") {
        action, index in
        print("myButton was tapped")
    }

    let patternImg = swipeCellButtons()
    myButton.backgroundColor = UIColor(patternImage: patternImg)

    return [myButton]
}

【讨论】:

  • 您的回答非常有帮助,让我取得了明显的进展。不过,我还没有完全完成。根据您的答案中的建议,我能够创建一个称为 swipeCellImage 的便捷函数,但我仍然有一些问题。我在这里重新提出了我的(新)问题:stackoverflow.com/questions/48554329/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2019-06-13
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2014-03-01
  • 2017-09-03
相关资源
最近更新 更多