以编程方式设置约束

时间:2019-11-03 16:05:52

标签: ios swift label constraints

我正在尝试添加带有标签的UIView,并希望设置约束以将标签水平和垂直放置在中心。但是代码没有按照我的意愿放置它。下面是代码。标签显示在屏幕的左上角,而不是屏幕的中心。

class TestViewController: UIViewController {
    var title = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        func presentTitle ()

    }

    func presentTitle () {
        title.backgroundColor = UIColor.black
        title.textColor = UIColor.white
        title.font = UIFont(name: "Helvetica", size: 30)
        title.textAlignment = .center
        title.backgroundColor = .lightGray
        title.numberOfLines = 1
        title..text = vmTitleTransferredFromTaskAnalysisDetail!
        self.view.addSubview(title)

        title.translatesAutoresizingMaskIntoConstraints = false
        title.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
        title.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
        title.eadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        title.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        self.view = title
    }
}

image

0 个答案:

没有答案