【问题标题】:how to set constraints programmatically in ios?如何在 ios 中以编程方式设置约束?
【发布时间】:2026-01-10 12:40:01
【问题描述】:

我需要在屏幕底部动态创建一个 UIView ,它需要水平包含 4 个按钮(例如 button1 、 button2 、 button3 、 button4 )。问题是我无法为其设置约束,谁能建议我。

感谢您的提前。

【问题讨论】:

  • 到目前为止您尝试过什么?请添加一些代码。这里有一个很好的关于设置约束的解释*.com/questions/31651022/…

标签: ios objective-c


【解决方案1】:

由于您希望有 4 个按钮,水平对齐,我建议您使用 UIStackViewvertical axis。您可以将其contentMode 设置为Fill Equally 并将您的4 个按钮作为子级添加到UIStackView。关于您的问题“如何以编程方式约束视图”,这就是您如何实现这一点(这只是高度等于 80 的屏幕底部的视图约束示例):

var yourView = UIView()
// Pin the leading edge of yourView  to the leading edge of the main view
yourView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true

// Pin the trailing edge of yourView to the leading trailing edge
yourView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true

// Pin the bottomedge of yourView to the margin's leading edge
yourView .bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true

// The height of your view
yourView.heightAnchor.constraintEqualToConstant(80).active = true

【讨论】:

  • 感谢您的回复。您能否在objective-c中指定这一点,对不起,我是ios新手。