facebookarchive / AsyncDisplayKit

Smooth asynchronous user interfaces for iOS apps.
http://asyncdisplaykit.org
Other
13.4k stars 2.2k forks source link

[ASCollectionNode] setup and cell height #2227

Closed ArEnSc closed 7 years ago

ArEnSc commented 8 years ago

Async Display Version:AsyncDisplayKit (1.9.90) The Cell height Size does not appear to automatically grow with the content as per documentation.


import Foundation

import AsyncDisplayKit

class AsyncChatViewController:UIViewController,ASCollectionDelegate,ASCollectionDataSource {

    internal var collectionNode:ASCollectionNode?

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.setupViewController()
    }
     // This function is called here because I am using a storyboard instance 
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setupViewController()
    }

    func setupViewController() {
        // setup flowlayout
        // size of each cell width is going to be the size of the screen width

        let screenSizeWidth = UIScreen.mainScreen().bounds.width
        let flowlayout = UICollectionViewFlowLayout.init()
        flowlayout.scrollDirection = .Vertical

// Shouldn't this be done automatically?  as per documentation ? remove this and it does not show cells.
        flowlayout.itemSize = CGSize.init(width: screenSizeWidth, height: 1000)
        self.collectionNode = ASCollectionNode.init(frame: CGRectZero, collectionViewLayout:flowlayout)
        self.collectionNode!.delegate   = self
        self.collectionNode!.dataSource = self
        self.collectionNode!.backgroundColor = UIColor.flatPlumColor()

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubnode(self.collectionNode!)
        self.collectionNode?.reloadData()
    }

    override func viewWillLayoutSubviews() {
        self.collectionNode!.frame = self.view.bounds
    }

    func collectionView(collectionView: ASCollectionView, nodeBlockForItemAtIndexPath indexPath: NSIndexPath) -> ASCellNodeBlock {

        func block() -> ASCellNode {

            let textNode:AsyncChatBubbleCell = AsyncChatBubbleCell.init(messageViewModel: MessageViewModel.init(message: "Hello"))

            return textNode
        }

        return block
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

The swift code to show the text

//
//  AsyncChatBubbleCell.swift
//  MassivelyChat
//
//  Created by mchung on 2016-09-09.
//  Copyright © 2016 mchung. All rights reserved.
//

import Foundation

import AsyncDisplayKit

enum MessageOwner {
    case BOT
    case CLIENT
}

struct MessageViewModel {
    var message:String
}

class AsyncChatBubbleCell:ASCellNode {

    var messageNode:ASTextNode?
    var profileImageNode:ASImageNode?

    enum direction {
        case Left
        case Right
    }

    init(messageViewModel:MessageViewModel) {
        super.init()
        let testMessage = "William Shakespeare (/ˈʃeɪkspɪər/;[1] 26 April 1564 (baptised) – 23 April 1616)[nb 1] was an English poet, playwright, and actor, widely regarded as the greatest writer in the English language and the world's pre-eminent dramatist.[2] He is often called England's national poet, and the .[3][nb 2] His extant works, including collaborations, consist of approximately 38 plays,[nb 3] 154 sonnets, two long narrative poems, and a few other verses, some of uncertain authorship. His plays have been translated into every major living language and are performed more often than those of any other playwright.[4] Shakespeare was born and brought up in Stratford-upon-Avon, Warwickshire. At the age of 18, he married Anne Hathaway, with whom he had three children: Susanna, and twins Hamnet and Judith. Sometime between 1585 and 1592, he began a successful career in London as an actor, writer, and part-owner of a playing company called the Lord Chamberlain's Men, later known as the King's Men. He appears to have retired to Stratford around 1613, at age 49, where he died three years later. Few records of Shakespeare's private life survive, which has stimulated considerable speculation about such matters as his physical appearance, sexuality, and religious beliefs, and whether the works attributed to him were written by others.[5] Shakespeare produced most of his known work between 1589 and 1613.[6][nb 4] His early plays were primarily comedies and histories, and these are regarded as some of the best work ever produced in these genres. He then wrote mainly tragedies until about 1608, including Hamlet, Othello, King Lear, and Macbeth, considered some of the finest works in the English language.[2] In his last phase, he wrote tragicomedies, also known as romances, and collaborated with other playwrights.Many of his plays were published in editions of varying quality and accuracy during his lifetime. In 1623, however, John Heminges and Henry Condell, two friends and fellow actors of Shakespeare, published a more definitive text known as the First Folio, a posthumous collected edition of his dramatic works that included all but two of the plays now recognised as Shakespeare's.[7] It was prefaced with a poem by Ben Jonson, in which Shakespeare is hailed, presciently, as.[7] In the 20th and 21st centuries, his works have been repeatedly adapted and rediscovered by new movements in scholarship and performance. His plays remain highly popular, and are constantly studied, performed, and reinterpreted in diverse cultural and political contexts throughout the world."

        let screenWidth = UIScreen.mainScreen().bounds.width
        self.backgroundColor = UIColor.flatGrayColor()
        self.messageNode = ASTextNode.init()

        self.messageNode?.attributedText = self.configureText(testMessage, size: 14)

        //self.messageNode?.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 1000)
        //let x = self.messageNode?.frameForTextRange(NSMakeRange(0,testMessage.characters.count))
        //self.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: x!.height)
        //self.messageNode?.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: x!.height)

        self.messageNode?.cornerRadius = 5
        self.messageNode?.clipsToBounds = true
        self.messageNode?.backgroundColor = UIColor.flatMintColor()
        self.messageNode?.maximumNumberOfLines = 0

        self.profileImageNode = ASImageNode.init()
        self.profileImageNode?.frame = CGRect.init(x: 0, y: 0, width: 64, height: 64)
        self.profileImageNode?.preferredFrameSize = self.profileImageNode!.bounds.size
        self.profileImageNode?.image = UIImage.init(named: "User.jpg")
        self.profileImageNode?.cornerRadius = self.profileImageNode!.frame.width/2.0
        self.profileImageNode?.clipsToBounds = true

        //self.addSubnode(self.profileImageNode!)
        self.addSubnode(self.messageNode!)
    }

    // This will size your items correctly.
    override func layoutSpecThatFits(constrainedSize: ASSizeRange) -> ASLayoutSpec {

        let hStack:ASStackLayoutSpec = ASStackLayoutSpec.init()

        hStack.setChildren([self.messageNode!])
        hStack.flexShrink = false
        hStack.direction = .Vertical

        let insets:UIEdgeInsets = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
        let layoutSpec = ASInsetLayoutSpec.init(insets: insets,child: hStack)

        return layoutSpec
    }

    func createBubbleMask() {

    }

    func configureText(text:String,size:CGFloat,color:UIColor=UIColor.flatWhiteColor(),textAlignment:NSTextAlignment = .Left) ->NSAttributedString {

        let attribString:NSMutableAttributedString = NSMutableAttributedString(string: text)
        let range = NSMakeRange(0, text.characters.count)
        attribString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(size), range: range)
        attribString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)

        let paragraphstyle = NSMutableParagraphStyle()
        paragraphstyle.alignment = textAlignment

//        paragraphstyle.headIndent = 5.0
//        paragraphstyle.firstLineHeadIndent = 5.0
//        paragraphstyle.tailIndent = -5.0
//        paragraphstyle.allowsDefaultTighteningForTruncation = true
        attribString.addAttribute(NSParagraphStyleAttributeName, value: paragraphstyle, range: range)

        return attribString
    }

}
ArEnSc commented 8 years ago

    func collectionView(collectionView: ASCollectionView, constrainedSizeForNodeAtIndexPath indexPath: NSIndexPath) -> ASSizeRange {
        let width = UIScreen.mainScreen().bounds.width
        return ASSizeRangeMake(CGSizeMake(width, 0), CGSizeMake(width, CGFloat.max))
    }

Found this nifty piece of code on the swift chat is this the best practice? thanks

hannahmbanana commented 8 years ago

@ArEnSc: Would it be possible to put this in a sample project for us? Thanks! I'm not exactly sure what you mean by it doesn't grow with the content. Does it show any text at all?

ArEnSc commented 8 years ago

@hannahmbanana Ill do it in 20 minutes! =)

ArEnSc commented 8 years ago

AsyncDemo.zip @hannahmbanana So in the documentation it says that the cell should grow with it's content, meaning that if it had text that grew a ASTextNode with multiple lines of text, the cell height should resize to accommodate that. I believe the reason why it did not grow by itself was due to the fact that the width of the ASCellNode was not set.

func collectionView(collectionView: ASCollectionView, constrainedSizeForNodeAtIndexPath indexPath: NSIndexPath) -> ASSizeRange {
    let width = UIScreen.mainScreen().bounds.width
    return ASSizeRangeMake(CGSizeMake(width, 0), CGSizeMake(width, CGFloat.max))
}

This piece of code was needed in order to fix that problem, which was not clear in the documentation perhaps add it in ? soon ?

garrettmoon commented 7 years ago

Going to close this out since it's community debugging and hasn't been commented on in a while.