【问题标题】:UILabel appear in debug view hierarchy but not in the applicationUILabel 出现在调试视图层次结构中,但不在应用程序中
【发布时间】:2015-06-25 02:43:13
【问题描述】:

我有一个 UIView,我通过 Interface Builder 在 ViewController 中添加。

在我的代码中,每次按下按钮时,我都会在此 UIView 中创建一个标签:

func addToDisplay(stringToDisplay: String) {
    let label = UILabel(frame: CGRectMake(0, 0, 10, 10))
    label.text = stringToDisplay
    label.textColor = UIColor.redColor()
    label.textAlignment = .Right
    label.sizeToFit()
    label.adjustsFontSizeToFitWidth = true
    label.minimumScaleFactor = 0.5
    label.setTranslatesAutoresizingMaskIntoConstraints(false)

    var lastLabel: UILabel?

    if displayView.subviews.count > 0 {
        lastLabel = displayView.subviews[displayView.subviews.count - 1] as? UILabel
    }

    displayView.addSubview(label)

    var viewsDictionary = ["displayView": displayView, "label": label]

    // add constraints
    if let lastLabel = lastLabel {
        viewsDictionary["lastLabel"] = lastLabel
        displayView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[label(==20)]-0-[lastLabel]", options: nil, metrics: nil, views: viewsDictionary))
    } else {
        displayView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[label(==20)]-0-|", options: nil, metrics: nil, views: viewsDictionary))
    }
    displayView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[label]-0-|", options: nil, metrics: nil, views: viewsDictionary)) 
}

当我按下按钮时,我的设备上(也没有在模拟器上)上什么都没有出现,但是当我检查视图调试层次结构时,它就在那里。我不明白为什么。有什么想法吗?

编辑:

这里有两张截图:

EDIT2:

通过将 alpha 更改为不同于 0 的值来解决...

【问题讨论】:

  • 我认为这是因为您没有给予适当的约束。 displayView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[label(30)]-0-|", options: nil, metrics: nil, views: viewsDictionary)) 这样试试
  • 让我再检查一遍
  • 不会将setTranslatesAutoresizingMaskIntoConstraints 设置为true
  • 顺便说一句,调试此类问题的最简单方法是使用po [self.view recursiveDescription] debugger 命令。您必须在布局后停止调试器(例如在viewDidAppear 中)。直观地检查视图层次结构很好,但以文本形式检查视图的属性和框架通常会更快地显示错误。
  • 太好了!但是当你记录一个 UIView 时,日志中也会提到 alpha。像这样,2015-04-18 14:16:33.505 MOPW[79905:8356851] <WeatherView: 0x7ffe3b4ef820; frame = (202 8; 110 30); alpha = 0; autoresize = RM+BM; layer = <CALayer: 0x7ffe3b4efb40>>。如果您共享了您的日志,其他人会更容易捕捉到错误。无论如何,快乐编码!

标签: ios swift autolayout uilabel


【解决方案1】:

我认为你需要告诉视图更新约束,写下这个并检查:

[displayView updateConstraintsIfNeeded];

同时测试您的displayView 是否已添加到self.view! 您在使用导航栏吗?如果是,那么是translucent 吗?如果是,那么您的 self.view 可能从 (0,0) 开始,而 Navigation Bar 位于其顶部。如果是这种情况,请给出一些 x & y,例如 (100, 100) 并检查它是否显示。

如果这有帮助,请告诉我们。

【讨论】:

  • updateConstraintsIfNeeded 不会改变任何事情。我没有使用导航栏,displayView 通过 Interface Builder 添加到 self.view。检查我的更新,我放了一些截图
猜你喜欢
  • 1970-01-01
  • 2015-06-10
  • 2021-08-01
  • 2023-03-11
  • 2018-09-14
  • 2017-07-11
  • 2014-06-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多