如何在没有Storyboard的情况下在UITableViewRowAction中自定义字体和颜色

我有经典的TableView,你可以删除项目,如果你滑动,而不是点击button。 我知道如何在单元格上设置自定义背景,但我无法find如何设置自定义字体和颜色。

谢谢你的帮助!

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in println("Delete button clicked!") }) deleteAction.backgroundColor = UIColor.redColor() return [deleteAction] } 

如何使用自定义字体?

这很容易。

  1. 首先,您需要将自定义字体文件包含到您的项目中。
  2. 接下来,转到您的info.plist文件,并用“ 应用程序提供的字体 ”键添加一个新条目。 请注意,这个入口应该是一个数组。
  3. 然后添加这些文件的名称作为这个数组的元素。

而就是这样! 所有你需要的就是像这样使用字体的名字

cell.textLabel.font = [UIFont fontWithName:@"FontName" size:16];

如何更改字体颜色?

更容易。 所有你需要的是

cell.textlabel.textcolor = UIColor.redColor()

编辑:

在你的情况下,你想改变RowAction的字体。 所以我想只有两个解决scheme。 一个使用[UIColor colorWithPatterImage:]

或者你可以用[[UIButton appearance] setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal]; 因为RowAction包含一个button。

那么,我发现设置自定义字体的唯一方法是使用UIAppearance协议的appearanceWhenContainedIn方法。 这个方法在Swift中尚不可用,所以你必须在Objective-C中完成。

我在一个实用的Objective-C类中做了一个类方法来设置它:

 + (void)setUpDeleteRowActionStyleForUserCell { UIFont *font = [UIFont fontWithName:@"AvenirNext-Regular" size:19]; NSDictionary *attributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: [UIColor whiteColor]}; NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString: @"DELETE" attributes: attributes]; /* * We include UIView in the containment hierarchy because there is another button in UserCell that is a direct descendant of UserCell that we don't want this to affect. */ [[UIButton appearanceWhenContainedIn:[UIView class], [UserCell class], nil] setAttributedTitle: attributedTitle forState: UIControlStateNormal]; } 

这工作,但绝对不是理想的。 如果你不包含UIView在收容层次结构中,那么它最终也会影响披露指标(我甚至没有意识到披露指标是一个UIButton子类)。 另外,如果单元格中的子视图内部有一个UIButton,那么该button也会受到此解决scheme的影响。

考虑到复杂性,最好使用一个更可定制的开源库来提供表格单元划动选项。

如果您使用XCode的Debug View层次结构查看UITableView在滑动button处于活动状态时发生了什么,则会看到UITableViewRowAction项目转换为包含在UITableViewCellDeleteConfirmationView名为_UITableViewCellActionButtonbutton。 更改button属性的一种方法是在将其添加到UITableViewCell时拦截它。 在你的UITableViewCell派生类中写下这样的东西:

 private let buttonFont = UIFont.boldSystemFontOfSize(13) private let confirmationClass: AnyClass = NSClassFromString("UITableViewCellDeleteConfirmationView")! override func addSubview(view: UIView) { super.addSubview(view) // replace default font in swipe buttons let s = subviews.flatMap({$0}).filter { $0.isKindOfClass(confirmationClass) } for sub in s { for button in sub.subviews { if let b = button as? UIButton { b.titleLabel?.font = buttonFont } } } } 

我想分享我的解决scheme为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>]; 只是将hexstring转换为UIColor。

检查示例输出截图。
在这里输入图像说明

这似乎工作,至less为设置字体颜色:

 - (void)setupRowActionStyleForTableViewSwipes { UIButton *appearanceButton = [UIButton appearanceWhenContainedInInstancesOfClasses:@[[NSClassFromString(@"UITableViewCellDeleteConfirmationView") class]]]; [appearanceButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal]; } 
 //The following code is in Swift3.1 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let rejectAction = TableViewRowAction(style: UITableViewRowActionStyle.default, title: "\u{2715}\nReject") { action, indexPath in print("didtapReject") } rejectAction.backgroundColor = UIColor.gray let approveAction = TableViewRowAction(style: UITableViewRowActionStyle.default, title: "\u{2713}\nApprove") { action, indexPath in print("didtapApprove") } approveAction.backgroundColor = UIColor.orange return [rejectAction, approveAction] } 

这里有一些可能有用的Swift代码:

 func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) ->[AnyObject]? { let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())] as Dictionary! UIButton.appearance().setAttributedTitle(NSAttributedString(string: "Your Button", attributes: attributes), forState: .Normal) // Things you do... } 

这将操纵你的应用程序中的所有button。

我认为你可以使用这个方法来改变外观只能在一个(或更多,你可以定义它)viewcontrollers:

  //create your attributes however you want to let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())] as Dictionary! //Add more view controller types in the [] UIButton.appearanceWhenContainedInInstancesOfClasses([ViewController.self]) 

希望这有助于。