ios - 尝试在 tableView :editActionsForRowAt: 中设置带有图像的按钮

标签 ios swift uitableview uitableviewrowaction

使用 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 像素):

enter image description here

这是它在 TableView 中的样子:

enter image description here

最佳答案

这是其中一种方式。您必须使用 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]
}

关于ios - 尝试在 tableView :editActionsForRowAt: 中设置带有图像的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483045/

相关文章:

ios - Binary Not Optimized for iPhone 5 - 包含所有图标

ios - 使用 IBOutlets 初始化 View Controller 以自定义 View

swift - 保存 map 图钉以便用户可以返回到之前使用 Swift 创建的图钉的最佳方法是什么?

ios - 如何获取包含子层的 View 的屏幕截图?

ios - UITableView 自定义单元格 - 如何将 cornerRadius 保持在编辑模式

c# - 打电话 ios xamarin

ios - 计算 TableView 中包含字符串的行数始终返回 1

ios - iPad 上 Springboard 中应用程序标题的字体大小

ios - UIView全屏

ios - 自定义 UITableViewCell 中的 UITextField 意外发现为 nil