How to add constraints programmatically using Swift

前端 未结 17 1180
逝去的感伤
逝去的感伤 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:28

    We can easily do this with in swift 5.1

    setup 1

    • subview align to view center
    • subview width height set using float

      view.addSubview(myView1)
      myView1.translatesAutoresizingMaskIntoConstraints = false
      NSLayoutConstraint.activate([
          myView1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
          myView1.centerYAnchor.constraint(equalTo: view.centerYAnchor),
          myView1.widthAnchor.constraint(equalToConstant: 100),
          myView1.heightAnchor.constraint(equalToConstant: 100),
      ])
      

    setup 2

    • subview align to view leading and top anchor
    • subview width set using view width height

          view.addSubview(myView2)
          myView2.translatesAutoresizingMaskIntoConstraints = false
      
          NSLayoutConstraint.activate([
              myView2.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 16),
              myView2.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 16),
              myView2.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.3),
              myView2.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3)
          ])
      

提交回复
热议问题