Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 UIView does not render UILabel when using addSubview programmatically

I have several use cases where I need to programmatically add a label and "container" views (e.g. UIView) to StackViews and other controls.

I cannot get the label to render and I am sure it is a simple layout flag that I am neglecting to set.

Example below: Programmatically render a UILabel with UIView.addSubview()

import UIKit

class TestViewController: UIViewController {

  var label = UILabel()
  var container = UIView()

  open override func viewDidLoad() {
    super.viewDidLoad()

    container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

    label.text = "Hello World!"
    label.textColor = .white


    container.addSubview(label)  // <- This does not work

    self.view.addSubview(container)

  }


}

The following block of code works, but does not take advantage of Autolayout. Any assistance would be appreciated.

import UIKit

class TestViewController: UIViewController {

  var label = UILabel()
  var container = UIView()

  open override func viewDidLoad() {
    super.viewDidLoad()

    container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

    label.text = "Hello World!"
    label.textColor = .white


    container.layout(label).topLeft() // <- This works

    self.view.addSubview(container)

  }


}
like image 859
Ryan Lee Avatar asked May 18 '26 14:05

Ryan Lee


1 Answers

Figured it out...

import UIKit

class TestViewController: UIViewController {

  var label = UILabel()
  var container = UIView()

  open override func viewDidLoad() {
    super.viewDidLoad()

    container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

    label.text = "Hello World!"
    label.textColor = .white
    label.frame = container.frame


    container.addSubview(label)

    self.view.addSubview(container)

  }


}
like image 108
Ryan Lee Avatar answered May 21 '26 13:05

Ryan Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!