iOS 11中的UITableViewRowAction太宽

时间:2017-09-14 05:21:21

标签: ios uitableview ios11

我使用以下技巧在表格视图行操作中包含图像:

How to manage equal width for UITableViewRowAction in iOS8.0?(More,Delete,etc actions)

UITableViewRowAction *completeAction = [UITableViewRowAction
                                        rowActionWithStyle:UITableViewRowActionStyleNormal
                                        title:@"   "
                                        handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
                                            ...
                                        }];
completeAction.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MyImageHere"]];

但它不再适用于iOS 11 - 行动作按钮的宽度对于我的图像来说太大了,所以它重复了:

Screenshot

这是否有解决方法?

更新

我最终使用了iOS 11中引入的新的尾随/前导上下文操作API:

https://developer.apple.com/documentation/uikit/uicontextualaction

此API允许您在操作中提供图像等。

#if defined __IPHONE_11_0 && __has_builtin(__builtin_available)

// This will be called on iOS 11+ if compiling with Xcode 9.

- (id)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (@available(iOS 11.0, *)) {
        UISwipeActionsConfiguration *configuration = ...
        return configuration;
    }
    return nil;
}

#endif

// This will be called on iOS 10 and older.

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView
                  editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Old style row actions.
}

请注意,如果使用Xcode 8编译这样的代码,则不会定义新的委托方法(并且您将看到该错误)。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并且能够修复它。但是,我的解决方案非常糟糕,需要一些解释:

我们必须实现一个自己的 UITableView ,它会在 LayoutSubviews()中修改它的子视图和子子视图的布局。 包含操作按钮的视图是 UISwipeActionPullView ,并且是子视图。此类型在编译时不可用(可能有人知道如何检查此类型?),但我们可以检查类型 UIKit.UIView 并检查视图是否具有相同数量的子视图( UIButton )我们定义了操作按钮。

我们希望避免我们的子视图比我们的操作按钮的宽度总和更宽。在这种情况下,我们需要修复 UISwipeActionPullView 的大小和位置。此外,我们需要修复 UIButton 的定位。

我的代码给出了三个固定宽度操作按钮的示例:

class CustomTableView: UITableView
{
    public CustomTableView(CGRect frame, UITableViewStyle style) : base(frame, style)
    {
    }

    public override void LayoutSubviews()
    {
        base.LayoutSubviews();
        var buttonSize = 54;

        foreach (var actionView in Subviews)
        {
            if (actionView.GetType().FullName == "UIKit.UIView" && actionView.Subviews.Length == 3)
            {
                if (actionView.Frame.Width >= buttonSize* 3)
                {
                    actionView.Frame = new CGRect(Frame.Width - 3 * buttonSize, actionView.Frame.Y, buttonSize* 3, buttonSize);
                    int i = 0;
                    foreach (var button in actionView.Subviews)
                    {
                        button.Frame = new CGRect(i * buttonSize, 0, buttonSize, buttonSize);
                        i++;
                    }
                }
            }
        }
    }
}