使用 AsyncDisplayKit 添加自定义按钮

Add custom Button with AsyncDisplayKit

我正在开发 IOS 应用程序。我使用 Facebook AsyncDisplayKit 库。我想要 ASNodeCell 中的一个按钮 Bu 我得到了“变量 'node' 在被块捕获时未初始化。 如何在 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];
});

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

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

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

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

虽然我建议您在此处使用 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];
  );
});