Set custom font for UITableView swipe action (UIContextualAction)

余生颓废 提交于 2020-05-28 04:42:19

问题


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

I have tried UIAppearance but without any luck...

Cheers! :)


回答1:


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

Standard font (Remove/Rename)

Custom font (Remove/Rename)

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



回答2:


I recently found out a way to do this by using the button titleLabel instead of the image property, so that you keep the ability to have an action with text and image.

As you will see, we need to do something awkward...


func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {

    if #available(iOS 13.0, *) {
        for subview in tableView.subviews {
            if NSStringFromClass(type(of: subview)) == "_UITableViewCellSwipeContainerView" {
                for swipeContainerSubview in subview.subviews {
                    if NSStringFromClass(type(of: swipeContainerSubview)) == "UISwipeActionPullView" {
                        for case let button as UIButton in swipeContainerSubview.subviews {
                            button.titleLabel?.font = .systemFont(ofSize: 12)
                        }
                    }
                }
            }
        }
    } else {
        for subview in tableView.subviews {
            if NSStringFromClass(type(of: subview)) == "UISwipeActionPullView" {
                for case let button as UIButton in subview.subviews {
                    button.titleLabel?.font = .systemFont(ofSize: 12)
                }
            }
        }
    }
 }



来源:https://stackoverflow.com/questions/56588715/set-custom-font-for-uitableview-swipe-action-uicontextualaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!