定位约束没有任何作用

时间:2018-11-12 02:34:11

标签: ios swift constraints nslayoutconstraint

我正在尝试在viewDidLoad函数中对标签进行编码。标签正在显示,但是我现在使用的代码不会影响位置。我正在尝试在viewDidLoad函数中编写所有代码。您可以在下面看到屏幕截图。

override func viewDidLoad() {
    super.viewDidLoad()

    let backbutton = UILabel()
    backbutton.backgroundColor = UIColor.orange
    backbutton.translatesAutoresizingMaskIntoConstraints = false
    backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true
    backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true
    backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true
    view.addSubview(backbutton)
}

enter image description here

3 个答案:

答案 0 :(得分:3)

这是将labelcenter的{​​{1}}对齐的方式,

view

以编程方式设置let backbutton = UILabel() view.addSubview(backbutton) backbutton.backgroundColor = UIColor.orange backbutton.translatesAutoresizingMaskIntoConstraints = false backbutton.widthAnchor.constraint(equalToConstant: 300).isActive = true backbutton.heightAnchor.constraint(equalToConstant: 300).isActive = true backbutton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true backbutton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true 时,请确保在应用constraints之前将view添加到super/parent view中。其次,在下面的几行中,您告诉constraints标签使其中心与其自身对齐(即 backbutton.centerXAnchor.constraint(equalTo:backbutton.centerXAnchor )。

backButton

由于要使其backbutton.centerXAnchor.constraint(equalTo: backbutton.centerXAnchor, constant: 100).isActive = true backbutton.centerYAnchor.constraint(equalTo: backbutton.centerYAnchor, constant: 300).isActive = true vertically与其horizontally居中对齐,因此应将parent view center设置为等于constraints如下,

parent view

enter image description here

答案 1 :(得分:2)

尝试一下!

 self.view.setNeedsUpdateConstraints()
    self.view.layoutIfNeeded()

答案 2 :(得分:0)

尝试改用CGRect:

            let screenWidth = UIScreen.main.bounds.width
            let screenHeight = UIScreen.main.bounds.height
            let xPostion:CGFloat = screenWidth - 150 //150 is half of view's width
            let yPostion:CGFloat = screenHeight - 150 //150 is half of view's height
            let buttonWidth:CGFloat = 300
            let buttonHeight:CGFloat = 300
            backbutton.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)

除了屏幕宽度/高度,您还可以尝试使用以下方法获取超级视图的宽度:

  self.view.frame.width 
  self.view.frame.height