以编程方式快速定位和约束

时间:2018-12-07 17:49:28

标签: ios swift uibutton uilabel constraints

我有以下观点:

enter image description here

我必须将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)
    }
}

我该怎么做?

1 个答案:

答案 0 :(得分: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),
])

与标签相同

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