简体   繁体   English

如何在 Swift 中以编程方式创建约束?

[英]How do I create constraints programmatically in Swift?

I am trying to set up the width of a UIButton using this code:我正在尝试使用以下代码设置UIButton的宽度:

constraintButtonPlayWidth = NSLayoutConstraint(item: buttonPlay,
        attribute: NSLayoutAttribute.Width,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self.view,
        attribute: NSLayoutAttribute.Width,
        multiplier: 1,
        constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)

But the button gets stretched too much;但是按钮被拉得太长了; probably because toItem: self.view .可能是因为toItem: self.view I tried modifying the constant of the constraint, but that didn't change anything.我尝试修改约束的常量,但这并没有改变任何东西。

How do I set up correctly this constraint so it actually has a width of 100?如何正确设置此约束,使其实际宽度为 100?

You were close.你很接近。 The constraint only should have a single item since it is not relative to another item.约束应该只有一个项目,因为它与另一个项目无关。

constraintButtonPlayWidth = NSLayoutConstraint (item: buttonPlay,
    attribute: NSLayoutAttribute.Width,
    relatedBy: NSLayoutRelation.Equal,
    toItem: nil,
    attribute: NSLayoutAttribute.NotAnAttribute,
    multiplier: 1,
    constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift中的Self Sizing Cell,如何以编程方式进行约束? - Self Sizing Cell in Swift, how do I make constraints programmatically? 以编程方式创建具有约束的UIbutton - create UIbutton programmatically with constraints in swift 如何以编程方式向UISegmentedControl添加约束 - How do I add constraints programmatically to UISegmentedControl 如何使用 Swift IOS 以编程方式创建布局和约束 - How to programmatically create layout and constraints using Swift IOS 如何以编程方式快速创建UITextField事件? - How do I create UITextField event programmatically in swift? 如何以编程方式创建布局约束 - How to Create layout constraints programmatically 约束如何以编程方式工作? - How do constraints work programmatically? 如何为我在Swift中以编程方式创建的UIViewController子类创建初始化? - How do I create the init for a UIViewController subclass that I create programmatically in Swift? 如果使用VFL以编程方式创建约束,如何为约束变化设置动画? - How do I animate constraint changes if constraints are created programmatically with VFL? 如何以编程方式将宽高比约束应用于自定义UICollectionViewCell? - How do I apply aspect ratio constraints to a custom UICollectionViewCell programmatically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM