Asyncdisplaykit
基本概念
AsyncDisplayKit的基本單元是node. ASDisplayNode是UIView和CALayer的抽象。ASDisplayNode是線程安全的,可以在工作線程中並行地初始化和配置整個node樹。
如果保證幀率到60fps,那么所有的layout和drawing需要在16ms內完成。由於系統的開銷,留給我們的只有大概10ms。
AsyncDisplayKit能夠將image decoding, text sizing和rendering以及其他耗時的UI操作剝離主線程。
nodes替代view
Node的API與UIView相似,而且可以直接訪問CALayer屬性。
添加view和layer,可以直接使用node.view 和 node.layer.
AsyncDisplayKit包括幾個強大的模塊:
* ASDisplayNode - 相當於UIView,子類化實現自定義nodes
* ASControlNode - 相當於UIControl,子類化實現buttons
* ASImageNode - 相當於UIimageView,異步decode image
* ASTextNode - 相當於UITextView,基於TextKit實現,支持富文本
* ASTableView - 相當於UITableView
我們可以直接用node替換UIKit,全部基於node實現的圖層樹的ASDK效率更高,但即使僅僅替換一個view也會提高效率。
首先我們在主線程 同步的使用node.
代碼示例:
_imageView = [[UIImageView alloc] init];
_imageView.image = [UIImage imageNamed:@"hello"];
_imageView.frame = CGRectMake(10.0f, 10.0f, 40.0f, 40.0f);
[self.view addSubview:_imageView];
使用Node替換:
_imageNode = [[ASImageNode alloc] init];
_imageNode.backgroundColor = [UIColor lightGrayColor];
_imageNode.image = [UIImage imageNamed:@"hello"];
_imageNode.frame = CGRectMake(10.0f, 10.0f, 40.0f, 40.0f);
[self.view addSubview:_imageNode.view];
這里我們沒有利用ASDK的異步 sizing 和 layout,但是性能已經有所提高。第一段代碼在主線程decode image,第二段代碼則在工作線程decode,而且可能在不同的CPU核心。
這里我們先展示了一個placeholder,然后再展示真實圖片。但是對於text,這種延遲加載的方法不可行,后面會進行討論。
Botton nodes
ASImageNode 和 ASTextNode 都繼承自ASControlNode,可以當做button使用,比如我們想做一個音樂播放器,先添加一個shuffle按鈕:
view controller的代碼:
- (void)viewDidLoad
{
[super viewDidLoad];
// attribute a string
NSDictionary *attrs = @{
NSFontAttributeName: [UIFont systemFontOfSize:12.0f],
NSForegroundColorAttributeName: [UIColor redColor],
};
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"shuffle"
attributes:attrs];
// create the node
_shuffleNode = [[ASTextNode alloc] init];
_shuffleNode.attributedString = string;
// configure the button
_shuffleNode.userInteractionEnabled = YES; // opt into touch handling
[_shuffleNode addTarget:self
action:@selector(buttonTapped:)
forControlEvents:ASControlNodeEventTouchUpInside];
// size all the things
CGRect b = self.view.bounds; // convenience
CGSize size = [_shuffleNode measure:CGSizeMake(b.size.width, FLT_MAX)];
CGPoint origin = CGPointMake(roundf( (b.size.width - size.width) / 2.0f ),
roundf( (b.size.height - size.height) / 2.0f ));
_shuffleNode.frame = (CGRect){ origin, size };
// add to our view
[self.view addSubview:_shuffleNode.view];
}
- (void)buttonTapped:(id)sender
{
NSLog(@"tapped!");
}
上述代碼可以正常運行,但是text的點擊區域太小,解決方法:
// size all the things
/* ... */
// make the tap target taller
CGFloat extendY = roundf( (44.0f - size.height) / 2.0f );
_shuffleNode.hitTestSlop = UIEdgeInsetsMake(-extendY, 0.0f, -extendY, 0.0f);
所有的nodes都可以使用Hit-test slops。