2

我正在开发一个 IOS 应用程序。我使用 Facebook AsyncDisplayKit 库。我想在 ASNodeCell 中添加一个按钮 我得到“变量‘节点’在被块捕获时未初始化。如何在 ASNodeCell 中添加 UIButton 或 UIWebView 控件。请帮助我

dispatch_queue_t _backgroundContentFetchingQueue;
    _backgroundContentFetchingQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

dispatch_async(_backgroundContentFetchingQueue, ^{
    ASDisplayNode *node = [[ASDisplayNode alloc] initWithViewBlock:^UIView *{
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button sizeToFit];
        node.frame = button.frame;
        return button;
    }];

                           // Use `node` as you normally would...
    node.backgroundColor = [UIColor redColor];

    [self.view addSubview:node.view];
});

在此处输入图像描述

4

1 回答 1

4

请注意,在您的情况下,不需要使用 UIButton,您可以使用 ASTextNode 作为按钮,因为它继承自 ASControlNode(ASImageNode 也是如此)。这在指南第一页的底部有描述:http: //asyncdisplaykit.org/guide/。这也将允许您在后台线程而不是主线程上进行文本大小调整(您在示例中提供的块在主队列上执行)。

为了完整起见,我还将评论您提供的代码。

您在创建块时尝试在块中设置节点的框架,因此您在初始化期间尝试在其上设置框架。这会导致你的问题。我认为您在使用 initWithViewBlock: 时实际上不需要在节点上设置框架:因为在内部 ASDisplayNode 使用该块直接创建其 _view 属性,该属性最终添加到视图层次结构中。

我还注意到您正在调用 addSubview: 从后台队列中,您应该始终在调用该方法之前将其分派回主队列。为方便起见,AsyncDisplayKit 还向 UIView 添加了 addSubNode:。

尽管我建议您在此处使用 ASTextNode,但我已更改您的代码以反映更改。

dispatch_queue_t _backgroundContentFetchingQueue;
_backgroundContentFetchingQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

dispatch_async(_backgroundContentFetchingQueue, ^{
ASDisplayNode *node = [[ASDisplayNode alloc] initWithViewBlock:^UIView *{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button sizeToFit];
    //node.frame = button.frame; <-- this caused the problem
    return button;
}];

                       // Use `node` as you normally would...
node.backgroundColor = [UIColor redColor];

// dispatch to main queue to add to view
dispatch_async(dispatch_get_main_queue(),
    [self.view addSubview:node.view];
    // or use [self.view addSubnode:node];
  );
});
于 2015-03-09T10:53:43.393 回答