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