这是一个简单的 ASDisplayNode 子类,其内容只是 2 个相互堆叠的 ASTextNode。如果辅助字符串不存在,我只希望在 ASDisplayNode 中有一个居中的 ASTextNode
如果我手动设置框架,我可以很好地布局元素,但我想使用布局堆栈来自动布局。
layoutSpecThatFits 根本没有被调用。如果我在 init 中对 self 调用 measure,我可以强制调用它,但是生成的 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
}
}