iosuitableviewuitableviewrowactionuicontextualactionuiswipeactionsconfiguration

Set custom font for UITableView swipe action (UIContextualAction)


How do you set a custom font for the title in UIContextualAction?

I have tried UIAppearance but without any luck...

Cheers! :)


Solution

  • I have found a way to do this by using the image property instead of the title...

    Standard font (Remove/Rename)

    Before/standard font

    Custom font (Remove/Rename)

    After/custom font

    To create an image of a label I have this extension:

    extension UIImage {
    
        /// This method creates an image of a view
        convenience init?(view: UIView) {
    
            // Based on https://stackoverflow.com/a/41288197/1118398
            let renderer = UIGraphicsImageRenderer(bounds: view.bounds)
            let image = renderer.image { rendererContext in
                view.layer.render(in: rendererContext.cgContext)
            }
    
            if let cgImage = image.cgImage {
                self.init(cgImage: cgImage, scale: UIScreen.main.scale, orientation: .up)
            } else {
                return nil
            }
        }
    }
    

    And then I simply have:

    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    
        let action = UIContextualAction(style: .destructive, title: nil) { action, view, completion in
            // Your swipe action code!
        }
        let label = UILabel()
        label.text = // Your swipe action text!
        label.font = // Your custom font!
        label.sizeToFit()
        action.image = UIImage(view: label)
    
        return UISwipeActionsConfiguration(actions: [action])
    }