如何在没有Storyboard的UITableViewRowAction中进行自定义字体和颜色

Vla*_*ser 11 iphone uitableview ios swift uitableviewrowaction

我有经典的TableView,如果你滑动而不是单击按钮,你可以删除项目.我知道如何在单元格上设置自定义背景,但我找不到如何设置自定义字体和颜色.

谢谢你的帮助!

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]
}
Run Code Online (Sandbox Code Playgroud)

Log*_*ier 11

好吧,我发现设置自定义字体的唯一方法是使用协议的appearanceWhenContainedIn方法UIAppearance.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];
}
Run Code Online (Sandbox Code Playgroud)

这有效,但绝对不理想.如果你没有在包含层次结构中包含UIView,那么它最终也会影响披露指标(我甚至没有意识到披露指标是一个UIButton子类).此外,如果您的单元格中的UIButton位于单元格中的子视图内,那么该按钮也会受到此解决方案的影响.

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

  • 我已经找到了这个答案的改进,以避免影响单元格内​​的其他按钮.在检查扩展单元格的视图层次结构后,我发现删除按钮位于`UITableViewCellDeleteConfirmationView`视图中.这是一个私有API,但使用它而不是'UIView`只针对删除按钮而不是单元格中的任何其他按钮.因此,而不是`[UIView类]`,使用`[NSClassFromString(@"UITableViewCellDeleteConfirmationView")类] (4认同)
  • 至少在 iOS 12 上对我不起作用。该按钮包含在名为“UISwipeActionPullView”的私有类视图中,因此您必须使用应该避免的“NSClassFromString” (2认同)

Ash*_*eeq -18

如何使用自定义字体?

这很容易。

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

就是这样!然后您所需要的就是按其名称使用字体,如下所示

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

如何更改字体颜色?

甚至更容易。所有你需要的是

cell.textlabel.textcolor = UIColor.redColor()

编辑:

在您的情况下,您想要更改 RowAction 的字体。所以我想到的只有2个解决方案。一用即用[UIColor colorWithPatterImage:]

或者您可以使用用户[[UIButton appearance] setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];,因为 RowAction 包含一个按钮。