How to Create layout constraints programmatically

前端 未结 5 633
-上瘾入骨i
-上瘾入骨i 2020-11-27 02:41

I am displaying a view in the bottom of the universal application and adding this view dynamically in my view. I want to show this view in bottom every time like iAd. in bot

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 03:04

    You can use autolayout constraints programmatically like below

    fileprivate func setupName(){
            let height = CGFloat(50)
    
            lblName.text = "Hello world"
            lblName.backgroundColor = .lightGray
    
            //Step 1
            lblName.translatesAutoresizingMaskIntoConstraints = false
    
            //Step 2
            self.view.addSubview(lblName)
    
            //Step 3
            NSLayoutConstraint.activate([
    
                lblName.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
                lblName.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
                lblName.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor,constant: -height),
                lblName.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
                ])
    
        }
    

    Output screenshot

提交回复
热议问题