为 UITableView 滑动操作设置自定义字体 (UIContextualAction)

Jen*_*zer 2 uitableview ios uitableviewrowaction uiswipeactionsconfiguration uicontextualaction

你如何为 中的标题设置自定义字体UIContextualAction

我试过了,UIAppearance但没有任何运气......

干杯! :)

Jen*_*zer 10

我找到了一种通过使用图像属性而不是标题来做到这一点的方法......

标准字体(删除/重命名)

之前/标准字体

自定义字体(删除/重命名)

后/自定义字体

要创建标签图像,我有这个扩展:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我只是:

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])
}
Run Code Online (Sandbox Code Playgroud)


小智 7

我最近找到了一种方法,通过使用按钮 titleLabel 而不是图像属性来执行此操作,这样您就可以保持对文本和图像进行操作的能力。

正如你将看到的,我们需要做一些尴尬的事情......


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

Run Code Online (Sandbox Code Playgroud)