Set constraints through code to an element from Storyboard with swift iOS8

前端 未结 3 1091
粉色の甜心
粉色の甜心 2020-12-21 16:22

I have a ViewController with a tableView. I\'ve set it up in the Storyboard. Is there a way to set the constraints for the tableView programmatically? I\'ve tried to set a I

3条回答
  •  不思量自难忘°
    2020-12-21 17:17

    Let's say you have a button named myButton and you would like to create its Bottom Space constraint via code. The constant of that constraint will be set to 500.

    Here's what a NSLayoutConstraint looks like in Swift. Make sure to include this code in a function.

        var constraintButton = NSLayoutConstraint (item: myButton,
            attribute: NSLayoutAttribute.Bottom,
            relatedBy: NSLayoutRelation.Equal,
            toItem: self.view,
            attribute: NSLayoutAttribute.Bottom,
            multiplier: 1,
            constant: 500)
    
        // Add the constraint to the view
        self.view.addConstraint(constraintButton)
    

提交回复
热议问题