Swiftgram/submodules/AsyncDisplayKit/docs/_docs/automatic-subnode-mgmt.md
Peter 9bc996374f Add 'submodules/AsyncDisplayKit/' from commit '02bedc12816e251ad71777f9d2578329b6d2bef6'
git-subtree-dir: submodules/AsyncDisplayKit
git-subtree-mainline: d06f423e0ed3df1fed9bd10d79ee312a9179b632
git-subtree-split: 02bedc12816e251ad71777f9d2578329b6d2bef6
2019-06-11 18:42:43 +01:00

13 KiB
Executable File

title layout permalink prevPage nextPage
Automatic Subnode Management docs /docs/automatic-subnode-mgmt.html batch-fetching-api.html inversion.html

Enabling Automatic Subnode Management (ASM) is required to use the Layout Transition API. However, apps that don't require animations can still benefit from the reduction in code size that this feature enables.

When enabled, ASM means that your nodes no longer require addSubnode: or removeFromSupernode method calls. The presence or absence of the ASM node and its subnodes is completely determined in its layoutSpecThatFits: method.

Example


Consider the following intialization method from the PhotoCellNode class in ASDKgram sample app. This ASCellNode subclass produces a simple social media photo feed cell.

In the "Original Code" we see the familiar addSubnode: calls in bold. In the "Code with ASM" these have been removed and replaced with a single line that enables ASM.

By setting .automaticallyManagesSubnodes to YES on the ASCellNode, we no longer need to call addSubnode: for each of the ASCellNode's subnodes. These subNodes will be present in the node hierarchy as long as this class' layoutSpecThatFits: method includes them.

Original code

Objective-C Swift
- (instancetype)initWithPhotoObject:(PhotoModel *)photo;
{
  self = [super init];

if (self) { _photoModel = photo;

_userAvatarImageNode = [[ASNetworkImageNode alloc] init];
_userAvatarImageNode.URL = photo.ownerUserProfile.userPicURL;
<b>[self addSubnode:_userAvatarImageNode];</b>

_photoImageNode = [[ASNetworkImageNode alloc] init];
_photoImageNode.URL = photo.URL;
<b>[self addSubnode:_photoImageNode];</b>

_userNameTextNode = [[ASTextNode alloc] init];
_userNameTextNode.attributedString = [photo.ownerUserProfile usernameAttributedStringWithFontSize:FONT_SIZE];
<b>[self addSubnode:_userNameTextNode];</b>

_photoLocationTextNode = [[ASTextNode alloc] init];
[photo.location reverseGeocodedLocationWithCompletionBlock:^(LocationModel *locationModel) {
  if (locationModel == _photoModel.location) {
    _photoLocationTextNode.attributedString = [photo locationAttributedStringWithFontSize:FONT_SIZE];
    [self setNeedsLayout];
  }
}];
<b>[self addSubnode:_photoLocationTextNode];</b>

}

return self; }

class PhotoCellNode {
  private let photoModel: PhotoModel
  
  private let userAvatarImageNode = ASNetworkImageNode()
  private let photoImageNode = ASNetworkImageNode()
  private let userNameTextNode = ASTextNode()
  private let photoLocationTextNode = ASTextNode()

  init(photo: PhotoModel) {
    photoModel = photo
    
    super.init()
    
    userAvatarImageNode.URL = photo.ownerUserProfile.userPicURL
    addSubnode(userAvatarImageNode)
    
    photoImageNode.URL = photo.URL
    addSubnode(photoImageNode)
    
    userNameTextNode.attributedText = poto.ownerUserProfile.usernameAttributedString(fontSize: fontSize)
    addSubnode(userNameTextNode)
    
    photo.location.reverseGeocodeLocation { [weak self] location in 
      if locationModel == self?.photoModel.location {
        self?.photoLocationTextNode.attributedText = photo.locationAttributedString(fontSize: fontSize)
        self?.setNeedsLayout()
      }
    }
    addSubnode(photoLocationTextNode)
  }
}

Code with ASM

Objective-C Swift
- (instancetype)initWithPhotoObject:(PhotoModel *)photo;
{
  self = [super init];

if (self) { self.automaticallyManagesSubnodes = YES;

_photoModel = photo;

_userAvatarImageNode = [[ASNetworkImageNode alloc] init];
_userAvatarImageNode.URL = photo.ownerUserProfile.userPicURL;

_photoImageNode = [[ASNetworkImageNode alloc] init];
_photoImageNode.URL = photo.URL;

_userNameTextNode = [[ASTextNode alloc] init];
_userNameTextNode.attributedString = [photo.ownerUserProfile usernameAttributedStringWithFontSize:FONT_SIZE];

_photoLocationTextNode = [[ASTextNode alloc] init];
[photo.location reverseGeocodedLocationWithCompletionBlock:^(LocationModel *locationModel) {
  if (locationModel == _photoModel.location) {
    _photoLocationTextNode.attributedString = [photo locationAttributedStringWithFontSize:FONT_SIZE];
    [self setNeedsLayout];
  }
}];

}

return self; }

class PhotoCellNode {
  private let photoModel: PhotoModel
  
  private let userAvatarImageNode = ASNetworkImageNode()
  private let photoImageNode = ASNetworkImageNode()
  private let userNameTextNode = ASTextNode()
  private let photoLocationTextNode = ASTextNode()

  init(photo: PhotoModel) {
    photoModel = photo
    
    super.init()
    
    automaticallyManagesSubnodes = true
    
    userAvatarImageNode.URL = photo.ownerUserProfile.userPicURL
    
    photoImageNode.URL = photo.URL
    
    userNameTextNode.attributedText = poto.ownerUserProfile.usernameAttributedString(fontSize: fontSize)
    
    photo.location.reverseGeocodeLocation { [weak self] location in 
      if locationModel == self?.photoModel.location {
        self?.photoLocationTextNode.attributedText = photo.locationAttributedString(fontSize: fontSize)
        self?.setNeedsLayout()
      }
    }
  }
}

Several of the elements in this cell - _userAvatarImageNode, _photoImageNode, and _photoLocationLabel depend on seperate data fetches from the network that could return at any time. When should they be added to the UI?

ASM knows whether or not to include these elements in the UI based on the information provided in the cell's ASLayoutSpec.

An ASLayoutSpec completely describes the UI of a view in your app by specifying the hierarchy state of a node and its subnodes. An ASLayoutSpec is returned by a node from its layoutSpecThatFits: method.

It is your job to construct a layoutSpecThatFits: that handles how the UI should look with and without these elements.

Consider the abreviated layoutSpecThatFits: method for the ASCellNode subclass above.

Objective-C Swift
- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{  
  ASStackLayoutSpec *headerSubStack = [ASStackLayoutSpec verticalStackLayoutSpec];
  headerSubStack.flexShrink         = YES;
  if (_photoLocationLabel.attributedString) {
    [headerSubStack setChildren:@[_userNameLabel, _photoLocationLabel]];
  } else {
    [headerSubStack setChildren:@[_userNameLabel]];
  }

_userAvatarImageNode.preferredFrameSize = CGSizeMake(USER_IMAGE_HEIGHT, USER_IMAGE_HEIGHT); // constrain avatar image frame size

ASLayoutSpec *spacer = [[ASLayoutSpec alloc] init]; spacer.flexGrow = YES;

UIEdgeInsets avatarInsets = UIEdgeInsetsMake(HORIZONTAL_BUFFER, 0, HORIZONTAL_BUFFER, HORIZONTAL_BUFFER); ASInsetLayoutSpec *avatarInset = [ASInsetLayoutSpec insetLayoutSpecWithInsets:avatarInsets child:_userAvatarImageNode];

ASStackLayoutSpec *headerStack = [ASStackLayoutSpec horizontalStackLayoutSpec]; headerStack.alignItems = ASStackLayoutAlignItemsCenter; // center items vertically in horizontal stack headerStack.justifyContent = ASStackLayoutJustifyContentStart; // justify content to the left side of the header stack [headerStack setChildren:@[avatarInset, headerSubStack, spacer]];

// header inset stack UIEdgeInsets insets = UIEdgeInsetsMake(0, HORIZONTAL_BUFFER, 0, HORIZONTAL_BUFFER); ASInsetLayoutSpec *headerWithInset = [ASInsetLayoutSpec insetLayoutSpecWithInsets:insets child:headerStack];

// footer inset stack UIEdgeInsets footerInsets = UIEdgeInsetsMake(VERTICAL_BUFFER, HORIZONTAL_BUFFER, VERTICAL_BUFFER, HORIZONTAL_BUFFER); ASInsetLayoutSpec *footerWithInset = [ASInsetLayoutSpec insetLayoutSpecWithInsets:footerInsets child:_photoCommentsNode];

// vertical stack CGFloat cellWidth = constrainedSize.max.width; _photoImageNode.preferredFrameSize = CGSizeMake(cellWidth, cellWidth); // constrain photo frame size

ASStackLayoutSpec *verticalStack = [ASStackLayoutSpec verticalStackLayoutSpec]; verticalStack.alignItems = ASStackLayoutAlignItemsStretch; // stretch headerStack to fill horizontal space [verticalStack setChildren:@[headerWithInset, _photoImageNode, footerWithInset]];

return verticalStack; }

override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
  let headerSubStack: ASStackLayoutSpec = .vertical()
  headerSubStack.style.flexShrink = 1

  if photoLocationLabel.attributedText != nil {
    headerSubStack.children = [userNameLabel, photoLocationLabel]
  } else {
    headerSubStack.children = [userNameLabel]
  }

  userAvatarImageNode.style.preferredSize = CGSize(width: userImageHeight, height: userImageHeight) //  constrain avatar image frame size

  let spacer = ASLayoutSpec()
  spacer.style.flexGrow = 1

  let avatarInsets = UIEdgeInsets(top: horizontalBuffer, left: 0, bottom: horizontalBuffer, right: horizontalBuffer)
  let avatarInset = ASInsetLayoutSpec(insets: avatarInsets, child: userAvatarImageNode)

  let headerStack: ASStackLayoutSpec = .horizontal()
  headerStack.alignItems = .center      // center items vertically in horizontal stack
  headerStack.justifyContent = .start   // justify content to the left side of the header stack
  headerStack.children = [avatarInset, headerSubStack, spacer]

  // header inset stack
  let insets = UIEdgeInsets(top: 0, left: horizontalBuffer, bottom: 0, right: horizontalBuffer)
  let headerWithInset = ASInsetLayoutSpec(insets: insets, child: headerStack)

  // footer inset stack
  let footerInsets = UIEdgeInsets(top: verticalBuffer, left: horizontalBuffer, bottom: verticalBuffer, right: horizontalBuffer)
  let footerWithInset = ASInsetLayoutSpec(insets: footerInsets, child: photoCommentsNode)

  // vertical stack
  let cellWidth = constrainedSize.max.width
  photoImageNode.style.preferredSize = CGSize(width: cellWidth, height: cellWidth)  // constrain photo frame size

  let verticalStack: ASStackLayoutSpec = .vertical()
  verticalStack.alignItems = .stretch   // stretch headerStack to fill horizontal space
  verticalStack.children = [headerWithInset, photoImageNode, footerWithInset]

  return verticalStack
}

Here you can see that the children of the headerSubStack depend on whether or not the _photoLocationLabel attributed string has returned from the reverseGeocode process yet.

The _userAvatarImageNode, _photoImageNode, and _photoCommentsNode are added into the ASLayoutSpec, but will not show up until their data fetches return.

Updating an ASLayoutSpec


**If something happens that you know will change your `ASLayoutSpec`, it is your job to call `setNeedsLayout`**. This is equivalent to `transitionLayout:duration:0` in the Transition Layout API. You can see this call in the completion block of the `photo.location reverseGeocodedLocationWithCompletionBlock:` call in the first code block.

An appropriately constructed ASLayoutSpec will know which subnodes need to be added, removed or animated.

Try out the ASDKgram sample app after looking at the code above, and you will see how simple it is to code an ASCellNode whose layout is responsive to numerous, individual data fetches and returns. While the ASLayoutSpec is coded in a way that leaves holes for the avatar and photo to populate, you can see how the cell's height will automatically adjust to accomodate the comments node at the bottom of the photo.

This is just a simple example, but this feature has many more powerful uses.

Warning: addSubnode: and removeFromSupernode should never be called on a node that has ASM enabled. Doing so could cause the following exception - "A flattened layout must consist exclusively of node sublayouts".