如何更改UITableViewRowAction标题颜色?

GJD*_*JDK 15 objective-c uitableview ios ios8 uitableviewrowaction

我在"editActionsForRowAtIndexPath"方法中使用了UITableViewRowAction.我可以更改UITableViewRowAction的backgroundcolor,但无法更改标题颜色.但我想改变UITableViewRowAction的颜色.关于这方面的任何意见都是值得注意的.

Pet*_*ger 18

有一种方法可以实现您的目标.但这有点棘手.

结果示例:

在此输入图像描述

这个技巧的想法是你可以实际修改背景颜色.这意味着您可以设置UIColor的+ colorWithPatternImage:并设置与所需样式匹配的位图图像.这可以通过使用图形编辑器创建图像或使用例如Core Graphics渲染来实现.此解决方案的唯一问题是,您必须使用特定的文本属性模仿原始标题长度才能使其正常工作,并且还必须将表视图行操作的标题设置为空格字符串,以便表视图单元格准备足够空间为您"自定义操作按钮".如果使用可变单元格行,在photoshop中创建静态png资产可能不合适.

这是NSString的类别,它创建一个空格的字符串,为您的自定义按钮创建空间,第二个将生成将作为背景图案图像放置的位图图像.对于参数,您必须为原始标题设置文本属性,基本上是@{NSFontAttributeName: [UIFont systemFontOfSize:18]}您所需的文本属性.也许有更好的方法来实现这一点:)

@implementation NSString (WhiteSpace)

- (NSString *)whitespaceReplacementWithSystemAttributes:(NSDictionary *)systemAttributes newAttributes:(NSDictionary *)newAttributes
{
    NSString *stringTitle = self;
    NSMutableString *stringTitleWS = [[NSMutableString alloc] initWithString:@""];

    CGFloat diff = 0;
    CGSize  stringTitleSize = [stringTitle sizeWithAttributes:newAttributes];
    CGSize stringTitleWSSize;
    NSDictionary *originalAttributes = systemAttributes;
    do {
        [stringTitleWS appendString:@" "];
        stringTitleWSSize = [stringTitleWS sizeWithAttributes:originalAttributes];
        diff = (stringTitleSize.width - stringTitleWSSize.width);
        if (diff <= 1.5) {
            break;
        }
    }
    while (diff > 0);

    return [stringTitleWS copy];
}

@end
Run Code Online (Sandbox Code Playgroud)

第二个重要的部分是渲染位图的代码,该位图可以用作UITableViewRowAction的backgroundColor的模式图像.

- (UIImage *)imageForTableViewRowActionWithTitle:(NSString *)title textAttributes:(NSDictionary *)attributes backgroundColor:(UIColor *)color cellHeight:(CGFloat)cellHeight
{
    NSString *titleString = title;
    NSDictionary *originalAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:18]};
    CGSize originalSize = [titleString sizeWithAttributes:originalAttributes];
    CGSize newSize = CGSizeMake(originalSize.width + kSystemTextPadding + kSystemTextPadding, originalSize.height);
    CGRect drawingRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, cellHeight));
    UIGraphicsBeginImageContextWithOptions(drawingRect.size, YES, [UIScreen mainScreen].nativeScale);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(contextRef, color.CGColor);
    CGContextFillRect(contextRef, drawingRect);

    UILabel *label = [[UILabel alloc] initWithFrame:drawingRect];
    label.textAlignment = NSTextAlignmentCenter;
    label.attributedText = [[NSAttributedString alloc] initWithString:title attributes:attributes];
    [label drawTextInRect:drawingRect];

    //This is other way how to render string 
    //    CGSize size = [titleString sizeWithAttributes:attributes];
    //    CGFloat x =  (drawingRect.size.width - size.width)/2;
    //    CGFloat y =  (drawingRect.size.height - size.height)/2;
    //    drawingRect.origin = CGPointMake(x, y);
    //    [titleString drawInRect:drawingRect withAttributes:attributes];

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

    return returningImage;
}
Run Code Online (Sandbox Code Playgroud)

然后,当您创建行动时,您可以执行以下操作:

NSDictionary *systemAttributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:18] };
NSDictionary *newAttributes = @{NSFontAttributeName: [UIFont fontWithName:@"Any font" size:15]};
NSString *actionTitle = @"Delete";
NSString *titleWhiteSpaced = [actionTitle whitespaceReplacementWithSystemAttributes:systemTextFontAttributes newAttributes:newAttributes];
UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:titleWhiteSpaced handle:NULL];
UIImage *patternImage = [self imageForTableViewRowActionWithTitle:actionTitle textAttributes:newAttributes backgroundColor:[UIColor redColor] cellHeight:50];
rowAction.backgroundColor = [UIColor colorWithPatternImage:patternImage]; 
Run Code Online (Sandbox Code Playgroud)

这个解决方案显然是hacky,但你可以在不使用私有API的情况下实现预期的结果,并且将来如果出现问题,这不会破坏你的应用程序.只有按钮看起来不合适.

结果示例:

在此输入图像描述

这段代码当然有很多改进的空间,任何建议都值得赞赏.


Lee*_*rew 9

迅速

不需要乱用UIButton.appearance ...

把它放在你的单元格的类中,并根据你的需要更改UITableViewCellActionButton.

override func layoutSubviews() {

    super.layoutSubviews()

    for subview in self.subviews {

        for subview2 in subview.subviews {

            if (String(subview2).rangeOfString("UITableViewCellActionButton") != nil) {

                for view in subview2.subviews {

                    if (String(view).rangeOfString("UIButtonLabel") != nil) {

                        if let label = view as? UILabel {

                            label.textColor = YOUR COLOUR
                        }

                    }
                }
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • @HassanTaleb我刚刚在iOS 11模拟器的Xcode 9中试过这个,这个hack不再有效.所以更新到Swift 4对你没什么帮助. (2认同)

Tho*_*ers 8

我担心没有办法改变UITableViewRowAction的标题颜色.

您可以在行动中改变的唯一事项是:

  • 背景颜色
  • 风格(破坏性(红色backgroundcolor,...)
  • 标题

有关详细信息,请参阅Apple Doc UITableViewRowAction


Tod*_*ddB 6

确实有一种方法可以更改UITableViewRowAction的标题颜色.这是一个按钮.您可以使用UIButton外观代理:

[[UIButton appearance] setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];

在此输入图像描述

  • 这是一个有趣的技巧,但它从那时起改变了所有UIButton的外观.因此,结果通常是不合需要的,因为UI中的许多其他按钮都会发生变化. (4认同)

Wit*_*ski 6

因此,在iOS 13天内仍然没有公共 api 可以更改textColorfont对单元格操作进行更改。

适用于 Swift 5.3、iOS 14 的工作解决方案

来自线程中答案的黑客攻击的结果非常不可靠,但我已经设法让我的黑客版本发挥作用。

1. 获取标签

这是我访问操作的简化方法UILabel

extension UITableViewCell {
    var cellActionButtonLabel: UILabel? {
        superview?.subviews
            .filter { String(describing: $0).range(of: "UISwipeActionPullView") != nil }
            .flatMap { $0.subviews }
            .filter { String(describing: $0).range(of: "UISwipeActionStandardButton") != nil }
            .flatMap { $0.subviews }
            .compactMap { $0 as? UILabel }.first
    }
}
Run Code Online (Sandbox Code Playgroud)

2. 更新布局更改的标签

接下来,layoutSubviews()在我的UITableViewCell子类中重写是不够的,因此我还必须重写layoutIfNeeded()才能使黑客工作。请注意,覆盖它们非常重要

override func layoutSubviews() {
    super.layoutSubviews()
    cellActionButtonLabel?.textColor = .black // you color goes here
}
override func layoutIfNeeded() {
    super.layoutIfNeeded()
    cellActionButtonLabel?.textColor = .black // you color goes here
}
Run Code Online (Sandbox Code Playgroud)

3.触发额外的布局刷新

难题的最后一部分是安排额外的颜色刷新,因此我们涵盖了由于某种原因上述函数不会被调用的所有情况。这样做的最佳地方是UITableViewDelegate方法..., willBeginEditingRowAt: ...

func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
        tableView.cellForRow(at: indexPath)?.layoutIfNeeded()
    }
}
Run Code Online (Sandbox Code Playgroud)

延迟布局刷新触发器的技巧是让 UIKit 首先配置单元格,这样我们就可以在定制之后立即跳转。0.01对我来说已经足够了,但我可能会因情况而异。

4、利润

现在您可以随心所欲地自定义标签!更改文本、颜色、字体或添加子视图!

不用说,如果苹果决定改变他们的私有实现,这种情况随时都可能被打破。


Dav*_*eek 5

Lee AndrewSwift 3/Swift 4中的回答:

class MyCell: UITableViewCell {

    override func layoutSubviews() {
        super.layoutSubviews()

        for subview in self.subviews {

            for sub in subview.subviews {

                if String(describing: sub).range(of: "UITableViewCellActionButton") != nil {

                    for view in sub.subviews {

                        if String(describing: view).range(of: "UIButtonLabel") != nil {

                            if let label = view as? UILabel {

                                label.textColor = UIColor.black

                            }

                        }

                    }

                }

            }

        }

    }

}
Run Code Online (Sandbox Code Playgroud)