UILabel appear in debug view hierarchy but not in the application

自闭症网瘾萝莉.ら 提交于 2020-01-03 12:27:03

问题


I have a UIView that I added in ViewController through the Interface Builder.

In my code, I create a label in this UIView every time that a button is pressed:

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)) 
}

When I press the button, nothing appear on my device (nor on the simulator) but when I check the view debug hierarchy, it's there. I don't understand why. Any idea?

EDIT:

Here are two screenshots:

EDIT2:

Solved by changing alpha to something different than 0...


回答1:


Well I think you need to tell the view to update constraints, write this and check:

[displayView updateConstraintsIfNeeded];

Also test that your displayView is added to self.view! Are you using Navigation Bar? If yes then is it translucent? If yes then your self.view may be starting from (0,0) and Navigation Bar is top of it. If this the case then give some x & y, say (100, 100) and check if it shows.

Let us know if this helped.



来源:https://stackoverflow.com/questions/29712899/uilabel-appear-in-debug-view-hierarchy-but-not-in-the-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!