How to add constraints programmatically using Swift

前端 未结 17 1167
逝去的感伤
逝去的感伤 2020-11-21 23:07

I\'m trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically

17条回答
  •  执念已碎
    2020-11-21 23:40

    Basically it involved 3 steps

    fileprivate func setupName() { 
    
        lblName.text = "Hello world"
    
        // Step 1
        lblName.translatesAutoresizingMaskIntoConstraints = false
    
        //Step 2
        self.view.addSubview(lblName)
    
        //Step 3
        NSLayoutConstraint.activate([
            lblName.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            lblName.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }
    

    This puts label "hello world" in center of screen.

    Please refer link Autolayout constraints programmatically

提交回复
热议问题