简体   繁体   English

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

[英]Set custom font for UITableView swipe action (UIContextualAction)

How do you set a custom font for the title in UIContextualAction ?如何在UIContextualAction为标题设置自定义字体?

I have tried UIAppearance but without any luck...我试过UIAppearance但没有任何运气......

Cheers!干杯! :) :)

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

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

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

Updated for Swift 5 & iOS 13为 Swift 5 和 iOS 13 更新

The following function allows you to set a font as well as a tint color to your swipe actions.以下功能允许您为滑动操作设置字体和色调。

To get started, add an extension to UITableView .首先,向UITableView添加一个扩展。

extension UITableView {
    /// Iterates over all subviews of a `UITableView` instance and applies the supplied font to all labels withing the UISwipeAction's array.
    /// - Parameter font: The font that should be applied to the labels.
    /// - Parameter tintColor: The tint color that should be applied to image views and labels
    /// - Parameter ignoreFirst: Whether or not the first swipe action should be ignored when applying tints
    public func setSwipeActionFont(_ font: UIFont, withTintColor tintColor: UIColor? = nil, andIgnoreFirst ignoreFirst: Bool = false) {
        for subview in self.subviews {
            //Confirm that the view being touched is within a swipe container
            guard NSStringFromClass(type(of: subview)) == "_UITableViewCellSwipeContainerView" else {
                continue
            }

            //Re-iterate subviews and confirm that we are touching a swipe view
            for swipeContainerSubview in subview.subviews {
                guard NSStringFromClass(type(of: swipeContainerSubview)) == "UISwipeActionPullView" else {
                    continue
                }

                //Enumerate subviews and confirm that we are touching a button
                for (index, view) in swipeContainerSubview.subviews.filter({ $0 is UIButton }).enumerated() {
                    //Set Font
                    guard let button = view as? UIButton else {
                        continue
                    }
                    button.titleLabel?.font = font
                    
                    //Set Tint Conditionally (based on index)
                    guard index > 0 || !ignoreFirst else {
                        continue
                    }
                    button.setTitleColor(tintColor, for: .normal)
                    button.imageView?.tintColor = tintColor
                }
            }
        }
    }
}

Within your delegate, add the following functionality to your UITableViewDataSource.WillBeginEditing(UITableView, IndexPath) method.在您的委托中,将以下功能添加到您的UITableViewDataSource.WillBeginEditing(UITableView, IndexPath)方法中。 Replace the font and colour params as you need.根据需要替换字体和颜色参数。 Tint colour is optional.色调颜色是可选的。

self?.tableView.setSwipeActionFont(.systemFont(ofSize: 24.0, withTintColor: .systemRed)

FOR OBJECTIVE C对于目标 C

Create a method创建方法

- (UIImage *)createImageFromLabel:(UILabel *)label
{
    UIGraphicsBeginImageContext(label.bounds.size);

    [label.layer renderInContext:UIGraphicsGetCurrentContext()];;

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

    return image;
}

This method will return image from your label.此方法将从您的标签返回图像。

Now in tableview datasource method现在在 tableview 数据源方法中

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIContextualAction *action = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        //Your code here
    }];

    action.backgroundColor = [UIColor redColor];

    // Create label as you want view for delete button
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontSize:14];
    label.text = @"Your Text";
    label.textColor = [UIColor whiteColor];
    [label sizeToFit];
    UIImage *image =  [self createImageFromLabel:label];

    action.image = image;

    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[action]];

    return actions;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在TableView中为UIContextualAction提供自定义宽度(滑动) - How to give custom width to UIContextualAction in TableView (swipe) 标题对于 UIContextualAction 不可见(UITableView 滑动删除 - iOS 11) - Title is not visible for UIContextualAction (UITableView swipe to delete - iOS 11) UITableView滑动操作可删除并使用自定义视图进行编辑 - UITableView swipe action delete and edit with custom view 如何通过滑动操作设置 UITableView 编辑模式? - How to set a UITableView Editing Mode from a swipe action? iOS 7-无法在自定义UITableView单元格中设置UITextView的字体颜色 - IOS 7 - Can't set font color of UITextView in custom UITableView cell 在滑动动作中更改UITableView的单元格内容 - Change cell content of UITableView in swipe action UISwipeGestureRecognizer使用UITableView的自定义操作 - UISwipeGestureRecognizer Custom Action with UITableView 如何为UITableview行操作按钮设置自定义图标? - How to set custom icon for UITableview row action buttons? UITableView - 破坏性UIContextualAction不会重新加载数据 - UITableView - Destructive UIContextualAction does not reload data 如何设置UIContextualAction的角半径? - How to set the corner radius of a UIContextualAction?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM