我想分享我的ObjC解决方案,这只是一个技巧,但对我来说可以正常工作。
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
// this just convert view to `UIImage`
UIImage *(^imageWithView)(UIView *) = ^(UIView *view) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
};
// This is where the magic happen,
// The width and height must be dynamic (it's up to you how to implement it)
// to keep the alignment of the label in place
//
UIColor *(^getColorWithLabelText)(NSString*, UIColor*, UIColor*) = ^(NSString *text, UIColor *textColor, UIColor *bgColor) {
UILabel *lbDelete = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 47, 40)];
lbDelete.font = [UIFont boldSystemFontOfSize:11];
lbDelete.text = text;
lbDelete.textAlignment = NSTextAlignmentCenter;
lbDelete.textColor = textColor;
lbDelete.backgroundColor = bgColor;
return [UIColor colorWithPatternImage:imageWithView(lbDelete)];
};
// The `title` which is `@" "` is important it
// gives you the space you needed for the
// custom label `47[estimated width], 40[cell height]` on this example
//
UITableViewRowAction *btDelete;
btDelete = [UITableViewRowAction
rowActionWithStyle:UITableViewRowActionStyleDestructive
title:@" "
handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"Delete");
[tableView setEditing:NO];
}];
// Implementation
//
btDelete.backgroundColor = getColorWithLabelText(@"Delete", [UIColor whiteColor], [YJColor colorWithHexString:@"fe0a09"]);
UITableViewRowAction *btMore;
btMore = [UITableViewRowAction
rowActionWithStyle:UITableViewRowActionStyleNormal
title:@" "
handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"More");
[tableView setEditing:NO];
}];
// Implementation
//
btMore.backgroundColor = getColorWithLabelText(@"More", [UIColor darkGrayColor], [YJColor colorWithHexString:@"46aae8"]);
return @[btMore, btDelete];
}
[YJColor colorWithHexString:<NSString>];
只是将十六进制字符串转换为 UIColor。
检查示例输出屏幕截图。