Search code examples
arraysasyncdisplaykit

Why ASTextNode not displaying?


I can not understand why the text is not displayed

enter image description here

import UIKit import AsyncDisplayKit

class ViewController: ASViewController {

init() {
    super.init(node: ASDisplayNode())
    let text = ASTextNode()
    let attrs = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue", size: 12.0)!]
    let string = NSAttributedString(string: "Hello World!", attributes: attrs)
    text.attributedText = string
    self.node.addSubnode(text)
}
required init?(coder aDecoder: NSCoder) {
    super.init(node: ASDisplayNode.init())
}

}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let window = UIWindow(frame: UIScreen.main.bounds)
    window.backgroundColor = UIColor.cyan
    window.rootViewController = ViewController()
    window.makeKeyAndVisible()
    self.window = window
    return true
}

Solution

  • import UIKit
    import AsyncDisplayKit
    
    class ViewController: ASViewController<ASDisplayNode>  {
        init() {
        super.init(node: LayoutExampleNode())
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(node: ASDisplayNode.init())
    }
    }
    
    class LayoutExampleNode: ASDisplayNode {
    override required init() {
        super.init()
        automaticallyManagesSubnodes = true
        backgroundColor = .white
    }
    
    }
    
    extension LayoutExampleNode {
    
    override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        let someVerticalStack = ASStackLayoutSpec.vertical()
        someVerticalStack.style.flexShrink = 1.0
        someVerticalStack.style.flexGrow = 1.0
    
        let text = ASTextNode()
        let attrs = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue", size: 12.0)!]
        let string = NSAttributedString(string: "Hello World!", attributes: attrs)
        text.attributedText = string
    
        someVerticalStack.children = [text]
    
        let someVerticalStackSpec = ASStackLayoutSpec(direction: .horizontal,
                                                spacing: 40,
                                                justifyContent: .start,
                                                alignItems: .center,
                                                children: [someVerticalStack])
    
        return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10), child: someVerticalStackSpec)
    }
    }