Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

ios - 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! :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...