UITableViewRowAction image for title

后端 未结 8 1814
情歌与酒
情歌与酒 2020-12-02 15:44

I made a custom UITableViewRowAction. Now I\'d like to add an image instead of the text. I know that it\'s possible but don\'t know how to do it. Does someone of you knows

8条回答
  •  渐次进展
    2020-12-02 16:11

    iOS 11.0

    Swift

    Apple introduced flexible way to declare row actions with great benefits.

    extension ViewController: UITableViewDelegate {
      func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let askAction = UIContextualAction(style: .normal, title: nil) { action, view, complete in
          print("Ask!")
          complete(true)
        }
    
        // here set your image and background color
        askAction.image = IMAGE
        askAction.backgroundColor = .darkGray
    
        let blockAction = UIContextualAction(style: .destructive, title: "Block") { action, view, complete in
          print("Block")
          complete(true)
        }
    
        return UISwipeActionsConfiguration(actions: [blockAction, askAction])
      }
    
      func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.textLabel?.text = "row: \(indexPath.row)"
      }
    }
    

    Example:

    iOS 8.0

    You need to set UIImage to backgroundColor of row action, concretely by:

    Swift:

    UIColor(patternImage: UIImage(named: "IMAGE_NAME"))
    

    Objective-C:

    [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMAGE_NAME"]];
    

提交回复
热议问题