繁体   English   中英

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

[英]Swift position and constraints programmatically

我有以下观点:

在此处输入图片说明

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

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

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)
    }
}

我怎么能那样做?

你可以试试

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),
])

标签相同

注意:由于按钮和标签有一个内在的内容 size ,那么我们不必设置 width && height

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM