将节点添加到子节点时不调用layoutSpecThatFits

时间:2016-03-29 18:26:16

标签: ios objective-c swift asyncdisplaykit

这是ASDisplayNode的一个简单子类,其内容只是2个ASTextNode堆叠在一起。如果辅助字符串不存在,我只想在ASDisplayNode中使用一个居中的ASTextNode

如果我手动设置框架,我可以很好地布局元素,但我想使用布局堆栈自动布局。

layoutSpecThat根本没有被调用。我可以强制它被调用,如果我在init中调用自我的测量,但结果primaryTextNode的帧是0,0,0,0 ...为什么layoutSpecThatFits根本没有被调用?如果我仅使用主字符串集调用measure,我也不确定为什么在调用布局规范之后它对于ASTextNode是零矩形。

class ContentNode : ASDisplayNode {

    var primaryAttributedString : NSAttributedString {
        didSet {
            primaryTextNode.attributedString = primaryAttributedString
        }
    }

    private lazy var primaryTextNode : ASTextNode = {
        let node = ASTextNode()
        node.attributedString = self.primaryAttributedString
        node.maximumNumberOfLines = 1;
        node.flexGrow = true
        //        node.frame = I need to manually set here, layout spec that fits not called
        self.addSubnode(node)
        return node
    }()

    var secondaryAttributedString : NSAttributedString? {
        didSet {
            if secondaryAttributedString != nil {
                secondaryTextNode.attributedString = secondaryAttributedString
            }
        }
    }

    private lazy var secondaryTextNode : ASTextNode = {
        let node = ASTextNode()
        node.attributedString = self.secondaryAttributedString
        node.maximumNumberOfLines = 1;
        //        node.frame = need to manually set here, layout spec that fits not called

        self.addSubnode(node)
        return node
    }()

    init(frame: CGRect, primaryText : NSAttributedString, secondaryText : NSAttributedString?) {
        self.primaryAttributedString = primaryText
        self.secondaryAttributedString = secondaryText
        super.init()
        self.frame = frame
        //        self.measure(frame.size)
        backgroundColor = UIColor.clearColor()
    }

    // THIS NEVER GETS CALLED (unless i do a self.measure call in init, and even then it does not layout the text node properly even with just the primary text node)
    override func layoutSpecThatFits(constrainedSize: ASSizeRange) -> ASLayoutSpec {
        var mainStackContent = [ASLayoutable]()
        mainStackContent.append(self.primaryTextNode)
        if nil != secondaryAttributedString {
            mainStackContent.append(secondaryTextNode)
        }
        let contentSpec = ASStackLayoutSpec(direction: .Vertical, spacing: 2, justifyContent: .Center, alignItems: .Center, children: mainStackContent)

        return contentSpec
    }
}

1 个答案:

答案 0 :(得分:1)

在ContentNode类中,您需要在每个文本节点上调用measure()。您可以在设置了belongsString属性后随时执行此操作。然后在实例化ContentNode的类中,您可能需要在实例上调用measure。我对最后一部分并不是100%肯定。当您访问实例的.view或.layer属性时,可能会隐式调用它。

我见过的layoutSpecThatFits的例子通常涉及ASTableView或ASCollectionView。这两个容器负责为你调用measure()。