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

标签 ios swift uibutton uilabel constraints

我有以下看法:

enter image description here

我必须在 Account balance 下方放置一个 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)
    }
}

我怎么做到的?

最佳答案

你可以试试

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

标签也一样

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

关于ios - 以编程方式快速定位和约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53674570/

相关文章:

ios - Swift-更改具有自己样式的 HTML 字符串上的字体

ios - 将时间戳转换为 NSDate

ios - 填充所有文本字段时如何启用按钮

uibutton - IBDesignable 用于 UIButton,IBInspectable 变量为零

ios - 如何知道一个对象是子类还是父类(super class)的实例

ios - 将按钮添加到单元格

ios - UIImagePickerController 崩溃应用程序 | swift 3,Xcode8

ios - 在 5 个像素而不是默认的 1 个像素后触摸拖动到 UIButton 内

ios - 从 UIView 委托(delegate)隐藏 UIViewController 中的按钮

Swift、Cocoapods 和 ios 7 兼容性、OAStackView