【问题标题】:Swift: adding a button programmatically without supplying a frame during initializationSwift:在初始化期间以编程方式添加按钮而不提供框架
【发布时间】:2017-01-22 12:45:56
【问题描述】:

假设我想以编程方式添加UIBUtton。每个UIView 构造函数都需要CGFrame,但在我的情况下,我希望大小是固有的,并且位置要锚定到超级视图的中心。

  • 如果我在不提供框架的情况下实例化 UIBUtton 元素,我会在调试视图层次结构中看到它,但在屏幕上看不到。
  • 如果我提供一个框架,我基本上会猜测大小,x,y 值会限制我稍后添加的约束。

以编程方式添加按钮的正确方法是什么?

谢谢!

编辑:没有CGFrame 的实例化没有问题。我没有看到按钮,因为我没有添加

button.translatesAutoresizingMaskIntoConstraints = false

这是由界面生成器自动完成的。

【问题讨论】:

  • let button = UIButton(), view.addSubview(button), 比添加约束。

标签: swift uiview constraints add programmatically


【解决方案1】:

如果您使用自动布局,请将translateAutoResizingMaskIntoConstraints 设置为false 并忽略框架,但不要忘记手动添加约束。

这是一个简单的例子:

override func viewDidLoad() {
    super.viewDidLoad()
    // no auto layout
    let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    v.backgroundColor = UIColor.blue
    view.addSubview(v)
    // with auto layout
    let v2 = UIView()
    v2.backgroundColor = UIColor.red
    // use auto layout
    v2.translatesAutoresizingMaskIntoConstraints = false
    // add width / height constraints
    v2.addConstraint(NSLayoutConstraint(item: v2, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
    v2.addConstraint(NSLayoutConstraint(item: v2, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
    // must add to hirarchy before adding the following constraints
    view.addSubview(v2)
    view.addConstraint(NSLayoutConstraint(item: v2, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 100))
    view.addConstraint(NSLayoutConstraint(item: v2, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
    // auto layout, visual format
    let v3 = UIView()
    v3.translatesAutoresizingMaskIntoConstraints = false
    v3.backgroundColor = UIColor.green
    let views = [ "v3" : v3 ]
    // must add v3 as subview before adding constraints referencing the parent view
    view.addSubview(v3)
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-200-[v3(100)]", options: [], metrics: nil, views: views))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[v3(100)]", options: [], metrics: nil, views: views))
}

对于许多视图,无需指定大小,因为某些视图通过intrinsicContentSize 提供了他们想要的大小。
您可以将其用于按钮以使它们具有“需要”的大小,或使用约束强制其他大小。
对于自定义视图 - 您可以覆盖此属性以提供您自己的“所需大小”逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多