Add custom Button with AsyncDisplayKit

与世无争的帅哥 提交于 2019-12-01 01:02:13

Note that in your case there's no need to use UIButton, you can use ASTextNode as a button since it inherits from ASControlNode (same goes for ASImageNode). This is described at the bottom of the first page of the guide: http://asyncdisplaykit.org/guide/. That will also allow you to do the text sizing on the background thread instead of the main thread (the block you provide in your example is executed on the main queue).

For completeness I'll also comment on the code you provided.

You're trying to set the frame of the node in the block when you're creating it, so you're trying to set the frame on it during its initialization. That causes your problem. I don't think you actually need to set the frame on the node when you're using initWithViewBlock: because internally ASDisplayNode uses the block to directly create its _view property which is added to the view hierarchy in the end.

I also noticed you're calling addSubview: from the background queue, you should always dispatch back to the main queue before you call that method. AsyncDisplayKit also adds addSubNode: to UIView for convenience.

I've changed you're code to reflect the changes though I recommend you use ASTextNode here.

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];
  );
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!