使用 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 像素):
这是它在 TableView 中的样子:
最佳答案
这是其中一种方式。您必须使用 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/