19.3 C
London
Monday, September 2, 2024

swift – iOS: When layoutIfNeeded() is named on a particular subview, it’s not displayed on the display


I’m dynamically including and displaying a customized view. Presently, the customized view has subviews.

When displaying a customized view and moreover displaying inner subviews, I’m curious as to why the place of that view is just not mirrored within the father or mother view if layoutIfNeeded() is named on a particular subview.

Beneath is my code.

last class RotationCardView: UIView {
  ...
  personal lazy var gradientLabel = GradientAnimatedLabel()

  override init(body: CGRect) {
    tremendous.init(body: body)
    ...
  }

  required init?(coder: NSCoder) { nil }

  override var intrinsicContentSize: CGSize {
    return CGSize(width: 200, top: 200)
  }

  func setGradientLabel() {
    let minimumTopSpacing = 5.0
    gradientLabel.textual content = "# cute cat card"
    gradientLabel.alpha = 0
    addSubview(gradientLabel)
    let gradientLabelBottomConstraint = gradientLabel.topAnchor.constraint(
    equalTo: bottomAnchor,
    fixed: minimumTopSpacing - gradientLabel.intrinsicContentSize.top/2)

    NSLayoutConstraint.activate([
      gradientLabelBottomConstraint,
      gradientLabel.trailingAnchor.constraint(equalTo: trailingAnchor)])
    self.layoutIfNeeded()
  }
}

I added this practice view to the ViewController’s view: After that I’ve logic to name setGradientLabel() when the button is pressed.

Once I name setGradientLabel(), the gradinetLabel is displayed after being laid out on the display.

However what I am interested in right here is when gradientLabel.layoutIfNeeded() is used as a substitute of self.layoutIfNeeded() inside the setGradientLabel() operate.

func setGradientLabel() {
  ...    
  // [comment1]
  NSLayoutConstraint.activate([
    gradientLabelBottomConstraint,
    gradientLabel.trailingAnchor.constraint(equalTo: trailingAnchor)])
  gradientLabel.layoutIfNeeded() // gradientLabel is just not displayed on the display.
}

As proven within the code snippet above, if I name layoutIfNeeded() of gradientLayer contained in the setGradientLabel() operate, [comment1] The structure added under is just not utilized and isn’t displayed on the display.

The image under is the view hierarchy.

enter image description here

Within the above code, to ensure that the gradientLabel I needed to be displayed immediately within the RotationCardView, is it fascinating to name layoutIfNeeded() on the view to which the gradientLabel constraint has been added?

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here