Swift - NSLayout Table 与 SpriteNodes 和 UILabel

Swift - NSLayout Table with SpriteNodes and UILabel

我仍在与 Xcode 和 Swift 一起开发我的第一个 iPhone 游戏。

游戏运行良好,所以我想我可以为游戏添加一些功能。其中之一是玩家可以看到他的统计数据的场景。

所以我为场景创建了一个背景 (SKSpriteNodes) 并且我在场景中添加了一些 UILabels

对于iPhone 6加上第一个UILabel在正确的位置(using NSLayout)

所以现在我已经在 iPhone 5 上对其进行了测试,例如 .. 它看起来像这样:

到目前为止我的代码..

func StatsLabelsAnzeigen(){
    StatHoechsteScoreLabel.textColor = SKColor.darkGrayColor()
    StatHoechsteScoreLabel.textAlignment = NSTextAlignment.Center
    StatHoechsteScoreLabel.font = UIFont.systemFontOfSize(16)
    StatHoechsteScoreLabel.alpha = 1
    StatHoechsteScoreLabel.translatesAutoresizingMaskIntoConstraints = false
    StatHoechsteScoreLabel.text = "\(HoechsteScore)" // (Int)

    self.view?.addSubview(StatHoechsteScoreLabel)

    // Create Constraints
    let RechtsbuendigStatHoechsteScoreLabel:NSLayoutConstraint = NSLayoutConstraint(item: self.view!, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: StatHoechsteScoreLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10)
    let ObenbuendigStatHoechsteScoreLabel:NSLayoutConstraint = NSLayoutConstraint(item: StatHoechsteScoreLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 168)
    let heightStatHoechsteScoreLabel = NSLayoutConstraint.constraintsWithVisualFormat("V:[StatHoechsteScoreLabel(40)]", options: [], metrics: nil, views: ["StatHoechsteScoreLabel" : StatHoechsteScoreLabel])
    let widthStatHoechsteScoreLabel = NSLayoutConstraint.constraintsWithVisualFormat("H:[StatHoechsteScoreLabel(200)]", options: [], metrics: nil, views: ["StatHoechsteScoreLabel" : StatHoechsteScoreLabel])

    // Add the created Constraints
    StatHoechsteScoreLabel.addConstraints(heightStatHoechsteScoreLabel)
    StatHoechsteScoreLabel.addConstraints(widthStatHoechsteScoreLabel)
    self.view?.addConstraint(RechtsbuendigStatHoechsteScoreLabel)
    self.view?.addConstraint(ObenbuendigStatHoechsteScoreLabel)

我的统计背景:

    StatsSceneBGNode = SKSpriteNode(imageNamed: "StatsBG2")
    StatsSceneBGNode.size = CGSize(width: view.frame.size.width*80/100, height: view.frame.size.height*80/100)
    StatsSceneBGNode.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
    StatsSceneBGNode.zPosition = 2
    StatsSceneBGNode.name = "StatsSceneBGNode"
    addChild(StatsSceneBGNode)

是否有可能以某种方式使约束更加灵活,以便它看起来适合每个 iPhone?

是的,最近 apple 使这比以前更容易了。 如果您在故事板中,则可以从标签拖到其他标签或拖到背景本身。您可以静态 space 对象,或动态分组并均匀地 space 它们。这是当您按住鼠标左键拖动到背景到滚动视图一侧时的样子: 和另一个对象(在本例中为按钮):

您可以使用右下角的小按钮对您的定位进行具体调整:

如果您希望以编程方式而不是通过情节提要来执行此操作,那么您可以在情节提要的 'View Controller Scene' 侧滚动条中找到用于编辑此类约束的变量名称。只需在情节提要中举几个你想做的事的例子(之后你可以删除),你就会看到它们的变量名: