【问题标题】:how to define preset height and width of object for constraint (Swift4)如何为约束定义对象的预设高度和宽度(Swift4)
【发布时间】:2018-09-01 01:33:33
【问题描述】:

我的代码以编程方式为 uitextfields 创建约束。它有效。我正在尝试优化我的编码实践并尝试找到一种方法来使用预设约束来确定所有文本字段的高度和宽度。如您所见,两者都是 a1。和 a2。是完全相同的高度和宽度。我想看看是否有一种方法可以为每个文本字段调用相同的高度和宽度,而不是总是对其进行编码。

 a1.translatesAutoresizingMaskIntoConstraints = false
    let leadingc2 = a1.widthAnchor.constraint(equalToConstant: 75)
    let trailingC2 = a1.heightAnchor.constraint(equalToConstant: 50)
    let topc2 = a1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -60)
    let bottomc2 = a1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -275)

    a1t = [leadingc2,trailingC2,topc2,bottomc2]

    NSLayoutConstraint.activate(a1t)

    //

    a2.translatesAutoresizingMaskIntoConstraints = false
    let leadingc22 = a2.widthAnchor.constraint(equalToConstant: 75)
    let trailingC22 = a2.heightAnchor.constraint(equalToConstant: 50)
    let topc22 = a2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 60)
    let bottomc22 = a2.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -275)

    a2t = [leadingc22,trailingC22,topc22,bottomc22]

    NSLayoutConstraint.activate(a2t)

【问题讨论】:

  • 您可以限制一个字段的尺寸等于另一个:a2.widthAnchor.constraint(equalTo: a1.widthAnchor).isActive = true

标签: ios swift4 nslayoutconstraint preset


【解决方案1】:
   //Make a variable?

   let height = 75


 //Or you can make a function to shorten the progress
   func setHeight (object : AnyObject?){
   object.heightAnchor.constraint(equalToConstant : 75).isActive =      true
  }

  //Then do
     setHeight(object : label1)

 // you can expand the function for height and other things (: or change it to set all of them programmatically really quick

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2014-07-03
    • 2012-10-10
    相关资源
    最近更新 更多