简体   繁体   English

如何在 UITableViewRowAction 中添加图像?

[英]How to add image in UITableViewRowAction?

I'm trying to add image in UITableView Swipe style.我正在尝试在UITableView Swipe 样式中添加图像。 I tried with Emoji text & its working fine我尝试使用表情符号文本及其工作正常

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  let editAction = UITableViewRowAction(style: .normal, title: "🖋") { (rowAction, indexPath) in
      print("edit clicked")
  }

  return [editAction]
}

But I need image instead of Emoji, meanwhile I tried但我需要图像而不是表情符号,同时我尝试了

editAction.backgroundColor = UIColor.init(patternImage: UIImage(named: "edit")!)

But it's getting duplicate image, I used images in many format like 20*20, 25*25, 50*50 but still duplicating.但它得到了重复的图像,我使用了多种格式的图像,如 20*20、25*25、50*50,但仍然重复。

How can I add image?如何添加图像?

Finally in iOS 11 , SWIFT 4 We can add add image in UITableView's swipe action with help of UISwipeActionsConfiguration最后在iOS 11 中SWIFT 4我们可以借助UISwipeActionsConfiguration在 UITableView 的滑动动作中添加添加图像

@available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

            let action =  UIContextualAction(style: .normal, title: "Files", handler: { (action,view,completionHandler ) in
                //do stuff
                completionHandler(true)
            })
        action.image = UIImage(named: "apple.png")
        action.backgroundColor = .red
        let configuration = UISwipeActionsConfiguration(actions: [action])

        return configuration
    }

WWDC video at 28.34 WWDC 视频 28.34

Apple Doc 苹果文档

Note: I have used 50*50 points apple.png image with 50 tableview row height注意:我使用了 50*50 点的 apple.png 图像和 50 tableview row height

I had the same problem with my project, so I did a workaround for this.我的项目遇到了同样的问题,所以我为此做了一个解决方法。 I think, this is helpful for you.我想,这对你有帮助。

When I swipe table cell to the left only for image width, it is working fine.当我只为图像宽度向左滑动表格单元格时,它工作正常。

在此处输入图片说明

But when I swipe table cell more than image width, table cell display like this:但是当我滑动表格单元格超过图像宽度时,表格单元格显示如下:

在此处输入图片说明

This happen because to add image I use 'backgroundColor' property.发生这种情况是因为要添加图像,我使用了 'backgroundColor' 属性。

copyButton.backgroundColor = UIColor(patternImage: UIImage(named: "bfaCopyIcon.png")!)

So to fix this, I increase image width to the same as table width.所以为了解决这个问题,我将图像宽度增加到与表格宽度相同。

old image >>>>>>>>>>>> new image旧图>>>>>>>>>>>>新图

在此处输入图片说明 >>>> >>>> 在此处输入图片说明

this is the new look:这是新外观:

在此处输入图片说明

This is my sample code:这是我的示例代码:

func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
    let copyButton = UITableViewRowAction(style: .normal, title: "") { action, index in

         print("copy button tapped")

    }
    copyButton.backgroundColor = UIColor(patternImage: UIImage(named: "bfaCopyIcon.png")!)


    let accessButton = UITableViewRowAction(style: .normal, title: "") { action, index in

       print("Access button tapped")

    }
    accessButton.backgroundColor = UIColor(patternImage: UIImage(named: "bfaAccess.png")!)


    return [accessButton, copyButton]
}

I came across this same problem and discovered a really good pod for this called SwipeCellKit that makes it really easy to implement an image into your swipe cell action without the swipe action causing multiple images to show.我遇到了同样的问题,并发现了一个非常好的 pod,称为SwipeCellKit ,它可以非常轻松地将图像实施到您的滑动单元格操作中,而不会导致滑动操作导致显示多个图像。 it also allows for more customization such as different swipe directions.它还允许更多的自定义,例如不同的滑动方向。

Steps:步骤:

  1. add pod添加豆荚
  2. import SwipeCellKit
  3. make cell conform to SwipeTableViewCell使单元格符合SwipeTableViewCell
  4. in cellForRow function set the cells delegate to selfcellForRow函数中将单元格委托设置为 self
  5. follow the implementation below or via the link按照下面的实现或通过链接

link to pod -> https://github.com/SwipeCellKit/SwipeCellKit pod 链接 -> https://github.com/SwipeCellKit/SwipeCellKit

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
    guard orientation == .right else { return nil }

    let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
        // handle action by updating model with deletion
    }

    // customize the action appearance
    deleteAction.image = UIImage(named: "delete")

    return [deleteAction]
}

func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
    var options = SwipeOptions()
    options.expansionStyle = .destructive
    return options
}

I found one way of doing this in SWIFT 3 -我在SWIFT 3 中找到了一种方法 -

在此处输入图片说明

 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        //let cell = tableView.cellForRow(at: indexPath)
        //print(cell?.frame.size.height ?? 0.0)//hence we need this height of image in points. make sure your contentview of image is smaller
        let deleteAction = UITableViewRowAction(style: .normal, title:"       ") { (rowAction, indexPath) in
            print("delete clicked")
        }
        deleteAction.backgroundColor = UIColor(patternImage:UIImage(named: "delete")!)
        return [deleteAction]
    }

We need to make sure our image dimension is matching with cell row height Here is my image which i used我们需要确保我们的图像尺寸与单元格行高匹配 这是我使用的图像在此处输入图片说明

Here is how I do it in objective-c and should work in swift when translated.这是我在objective-c做法,翻译时应该swift

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *deleteString = @"Delete";
    CGFloat tableViewCellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    UIImage *image = [UIImage imageNamed:@"delete_icon"];

    CGFloat fittingMultiplier = 0.4f;
    CGFloat iOS8PlusFontSize = 18.0f;
    CGFloat underImageFontSize = 13.0f;
    CGFloat marginHorizontaliOS8Plus = 15.0f;
    CGFloat marginVerticalBetweenTextAndImage = 3.0f;

    float titleMultiplier = fittingMultiplier;

    NSString *titleSpaceString= [@"" stringByPaddingToLength:[deleteString length]*titleMultiplier withString:@"\u3000" startingAtIndex:0];

    UITableViewRowAction *rowAction= [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:titleSpaceString handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
        //Do Stuff
    }];

    CGSize frameGuess=CGSizeMake((marginHorizontaliOS8Plus*2)+[titleSpaceString boundingRectWithSize:CGSizeMake(MAXFLOAT, tableViewCellHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:iOS8PlusFontSize] } context:nil].size.width, tableViewCellHeight);

    CGSize tripleFrame=CGSizeMake(frameGuess.width*3.0f, frameGuess.height*3.0f);

    UIGraphicsBeginImageContextWithOptions(tripleFrame, YES, [[UIScreen mainScreen] scale]);
    CGContextRef context=UIGraphicsGetCurrentContext();

    [[UIColor blueColor] set];
    CGContextFillRect(context, CGRectMake(0, 0, tripleFrame.width, tripleFrame.height));

    CGSize drawnTextSize=[deleteString boundingRectWithSize:CGSizeMake(MAXFLOAT, tableViewCellHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:underImageFontSize] } context:nil].size;

    [image drawAtPoint:CGPointMake((frameGuess.width/2.0f)-([image size].width/2.0f), (frameGuess.height/2.0f)-[image size].height-(marginVerticalBetweenTextAndImage/2.0f)+2.0f)];

    [deleteString drawInRect:CGRectMake(((frameGuess.width/2.0f)-(drawnTextSize.width/2.0f))*([[UIApplication sharedApplication] userInterfaceLayoutDirection]==UIUserInterfaceLayoutDirectionRightToLeft ? -1 : 1), (frameGuess.height/2.0f)+(marginVerticalBetweenTextAndImage/2.0f)+2.0f, frameGuess.width, frameGuess.height) withAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:underImageFontSize], NSForegroundColorAttributeName: [UIColor whiteColor] }];

    [rowAction setBackgroundColor:[UIColor colorWithPatternImage:UIGraphicsGetImageFromCurrentImageContext()]];
    UIGraphicsEndImageContext();

    return @[rowAction];
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let write = UITableViewRowAction(style: .default, title: "\u{1F58A}") { action, index in
        print("edit button tapped")
    }

    return [write]
}

try this used unicode instead icon.试试这个使用 unicode 代替图标。 this will work这会起作用

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM