这是 ASDisplayNode 的一个简单子(monad)类,其内容只是 2 个 ASTextNode 相互堆叠。如果辅助字符串不存在,我只需要 ASDisplayNode 中的单个居中 ASTextNode
如果我手动设置框架,我可以很好地布置元素,但我想使用布局堆栈来自动布置元素。
layoutSpecThatFits 根本没有被调用。如果我在 init 中对 self 调用 measure,我可以强制调用它,但是生成的 primaryTextNode 的框架是 0,0,0,0 ...为什么根本不调用 layoutSpecThatFits?如果我仅使用主字符串集调用测量,我也不确定为什么在调用布局规范后它对于 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
}
}
最佳答案
在您的 ContentNode 类中,您需要在每个文本节点上调用 measure() 。在设置 attributedString 属性后,您可以随时执行此操作。然后在实例化 ContentNode 的类中,您可能需要在实例上调用 measure。我对最后一部分不是 100% 确定。当您访问实例的 .view 或 .layer 属性时,它可能会被隐式调用。
我看到的layoutSpecThatFits的例子一般都会涉及到ASTableView或者ASCollectionView。这两个容器负责为您调用 measure()。
关于ios - 将节点添加到子节点时不会调用 layoutSpecThatFits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36292241/