【问题标题】:Swift position and constraints programmatically以编程方式快速定位和约束
【发布时间】:2019-05-09 12:25:15
【问题描述】:

我有以下看法:

我必须在帐户余额下方放置一个UIButtonUILabel,具体取决于此移动是否被拒绝(只需检查一个变量)。

我已经根据它以编程方式创建了按钮和标签,但我不知道如何将它添加到该特定位置并添加约束。

func checkRejected () {
    if !movement.rejected {
        let xposition = amountLabel.frame.origin.x
        let yposition = balanceLabel.frame.origin.y + 300
        let button = UIButton(frame: CGRect(x: xposition, y: yposition, width: 100, height: 50))
        button.setTitle("Reject", for: .normal)
        button.setTitleColor(UIColor.blue, for: .normal)
        button.addTarget(self, action: #selector(rejectAction), for: .touchUpInside)
        self.view.addSubview(button)
    }
    else {
        let xposition = amountLabel.frame.origin.x
        let yposition = balanceLabel.frame.origin.y + 300
        let label = UILabel(frame: CGRect(x: xposition, y: yposition, width: 100, height: 50))
        label.text = "Rejected"
        label.textColor = UIColor.red
        self.view.addSubview(label)
    }
}

我怎么能这样做?

【问题讨论】:

  • 还要考虑是否需要 300 或 30,因为它可能会超过某些 iphone 的屏幕高度
  • 这当然可以用代码来完成,但如果其他所有内容都在故事板中,请在故事板中添加按钮和约束,然后将其hidden 属性设置为YES不想看到。

标签: ios swift uibutton uilabel constraints


【解决方案1】:

你可以试试

self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([ 
    button.topAnchor.constraint(equalTo: self.balanceLabel.bottomAnchor,constant:30),
    button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
])

标签也一样

注意:由于按钮和标签具有固有的内容大小,因此我们不必设置宽度和高度

【讨论】:

  • 那么,我们要做的是:首先将按钮放在距离标签下方30处,然后在X轴上居中,不是吗?
  • 那么 button.translatesAutoresizingMaskIntoConstraints 呢?抱歉,这是我第一次以编程方式设置约束
  • 您应该始终将其设置为 false 以便以编程方式创建约束,请阅读 developer.apple.com/documentation/uikit/uiview/…
猜你喜欢
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多