UITableViewRowAction图像的标题

我做了一个自定义的UITableViewRowAction。 现在我想添加一个图像,而不是文本。 我知道这是可能的,但不知道如何去做。 你们中的某个人是否知道如何在Swift中做到这一点,并想帮助我? 感谢您的回答!

你需要将UIImage设置为行动的backgroundColor,具体做法是:

迅速:

UIColor(patternImage: UIImage(named: "")) 

Objective-C的:

 [UIColor colorWithPatternImage:[UIImage imageNamed:@""]]; 
 class TableViewRowAction: UITableViewRowAction { var image: UIImage? func _setButton(button: UIButton) { if let image = image, let titleLabel = button.titleLabel { let labelString = NSString(string: titleLabel.text!) let titleSize = labelString.sizeWithAttributes([NSFontAttributeName: titleLabel.font]) button.tintColor = UIColor.whiteColor() button.setImage(image.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) button.imageEdgeInsets.right = -titleSize.width } } } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let delete = TableViewRowAction(style: UITableViewRowActionStyle.Default, title: " ") { action, indexPath in } delete.image = UIImage(named: "trashImg") let sharing = TableViewRowAction(style: UITableViewRowActionStyle.Default, title: " ") { action, indexPath in } sharing.backgroundColor = UIColor.lightGrayColor() sharing.image = UIImage(named: "sharingImg") return [delete, sharing] } 
 delActions.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"delete.png"]]; 

基本的图案颜色方法的问题是你的图像需要与动作button的尺寸相同,或者至less在底部有更平坦的背景以防止图像重复(即使它将被锚定顶部,这是不是很好)。

我不得不处理dynamic高度单元格,所以我实现了以下内容:

 - (UIColor *)backgroundImageForActionAtIndexPath:(NSIndexPath *)indexPath withImage:(UIImage *)image tintColor:(UIColor *)tintColor backgroundColor:(UIColor *)backgrounfColor expectedWith:(CGFloat)width { // CGRect cellFrame = [self.tableView rectForRowAtIndexPath:indexPath]; CGSize expectedSize = CGSizeMake(width, cellFrame.size.height); UIGraphicsBeginImageContextWithOptions(expectedSize, NO, 0.0); CGContextRef ctx = UIGraphicsGetCurrentContext (); if (ctx) { // set the background CGContextSetFillColorWithColor(ctx, backgrounfColor.CGColor); CGRect fillRect = CGRectZero; fillRect.size = expectedSize; CGContextFillRect(ctx, fillRect); // put the image CGContextSetFillColorWithColor(ctx, tintColor.CGColor); CGRect rect = CGRectMake((expectedSize.width - image.size.width) / 2., (expectedSize.height - image.size.height) / 2., image.size.width, image.size.height); [image drawInRect:rect]; } UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return [UIColor colorWithPatternImage:newImage]; 

}

您仍然必须设置expectedWidth,以便与您在动作标题中放置的空白标签相匹配。 例如:@“” – > 64.f

正如您所看到的,您可以在代码中设置button的背景和色调,而不是在艺术品本身。