Objective-C 从不兼容的类型块分配给 UIView

Objective-C Assigning to UIView from incompatible type block

我试图将 UIView 分配给带有块的 UITableView 页脚。

这很好用:

UIView* (^createFooter)() = ^UIView*{
            UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,100)];
            return footer;
            };
myTableView.tableFooterView = createFooter();

为什么这不起作用:

myTableView.tableFooterView = ^UIView*{
            UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,100)];
            return footer;
            };

感谢您告诉我使用块时我错过了什么!

上面的代码是定义一个块并调用块来return一个视图。 下面的代码是将一个块分配给一个视图,所以错误!

您可以像这样多次调用一个块:

myTableView.tableFooterView = createFooter();
myTableView.tableHeaderView = createFooter();

createFooter() 是由

定义的块
^UIView*{
            UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,100)];
            return footer;
            };

这不是 UIView 值。

在您提供的第一个示例中,您在第一行声明您的块,然后在第二行调用它。调用块由 () 隐含,你在第二行。

在您的第二个示例中,您将视图指定为块而不是调用该块的结果。您需要在末尾添加一个 () 才能实际调用您声明为内联的块。所以,而不是

myTableView.tableFooterView = ^UIView *{ ... };

你需要

myTableView.tableFooterView = ^UIView *{ ... }();