如何执行激活程序约束

时间:2018-12-30 13:47:38

标签: ios swift constraints

我已经编写了一个函数,该函数定义了UILabel并将其添加到UIView-但是由于标签仍保留在屏幕的左上角,因此未执行约束。

此处提供代码:

func timeAdded(screenHeight: CGFloat, screenWidth: CGFloat, viewController: UIView) {


    let readyLabel = UILabel()
    readyLabel.backgroundColor = UIColor.white
    readyLabel.textAlignment = .center
    readyLabel.text = "00:00"
    readyLabel.textColor = UIColor.blue
    //readyLabel.alpha = 0
    readyLabel.font = UIFont(name: "panl-font-4", size: 60)
    readyLabel.sizeToFit()

    viewController.addSubview(readyLabel)

    readyLabel.centerXAnchor.constraint(equalTo: viewController.centerXAnchor, constant: 0).isActive = true
    readyLabel.centerYAnchor.constraint(equalTo: viewController.centerYAnchor, constant: 0).isActive = true

}

任何建议表示赞赏

1 个答案:

答案 0 :(得分:1)

您可能需要

readyLabel.translatesAutoresizingMaskIntoConstraints = false 
NSLayoutConstraint.activate([
    readyLabel.centerXAnchor.constraint(equalTo: viewController.centerXAnchor)
    readyLabel.centerYAnchor.constraint(equalTo: viewController.centerYAnchor)
])

因此最好阅读This