嗨,我正在以编程方式添加一些像这样的 View
let xPos = (self.view.frame.size.width - 200)/2
self.headerLabel = UILabel(frame: CGRect(x: xPos, y: 50.0, width: 200.0, height: 100.0))
self.shopButton = UIButton(frame: CGRect(x: xPos, y: 150.0, width: 200.0, height: 40.0))
self.createButton = UIButton(frame: CGRect(x: xPos, y: 230.0, width: 200.0, height: 40.0))
self.orLabel = UILabel(frame: CGRect(x: xPos, y: 200.0, width: 200.0, height: 20.0))
问题是当我将设备旋转到横向模式时,反之亦然,我的 View 与左侧对齐。我该如何预防?
最佳答案
使用NSLayoutContaint
将 View 中的约束添加到其 super View
例如
let horizontalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerX, relatedBy: .equal, toItem: view.superview, attribute: .centerX, multiplier: 1, constant: 1)
horizontalConstraint.isActive = true
let verticalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerY, relatedBy: .equal, toItem: view.superview, attribute: .centerY, multiplier: 1, constant: 1)
verticalConstraint.isActive = true
关于ios - 以编程方式添加 View 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488253/