OGeek|极客世界-中国程序员成长平台

标题: ios - 以编程方式使用 addSubview 时,Swift 3 UIView 不呈现 UILabel [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:08
标题: ios - 以编程方式使用 addSubview 时,Swift 3 UIView 不呈现 UILabel

我有几个用例,我需要以编程方式将标签和“容器” View (例如 UIView)添加到 StackView 和其他控件。

我无法让标签呈现,我确信这是一个我忽略设置的简单布局标志。

以下示例:使用 UIView.addSubview() 以编程方式呈现 UILabel

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)

  }


}

以下代码块有效,但没有利用自动布局。如有任何帮助,我们将不胜感激。

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)

  }


}



Best Answer-推荐答案


想通了...

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)

  }


}

关于ios - 以编程方式使用 addSubview 时,Swift 3 UIView 不呈现 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075832/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4