我注意到,当我以编程方式更新自动布局约束时,在旋转屏幕时会恢复所有更改.
重现问题:
带有UIView的基本Storyboard界面和2个约束:
使用IBOutlet创建并链接这两个约束
对我来说似乎是一个错误.
你怎么看 ?
截图:
约束#1:
约束#2:
已安装是指安装大小类,而不是活动/非活动.
您必须以编程方式创建另一个约束,并激活/停用该约束.这是因为您无法更改约束的乘数(我可以更改NSLayoutConstraint的乘数属性吗?),也不能修改大小类(activateConstraints:和deactivateConstraints:在IB中创建的约束后不会保持旋转).
有几种方法可以做到这一点.在下面的示例中,我使用乘数或1/2创建x1约束的副本.然后我在两者之间切换:
@IBOutlet var fullWidthConstraint: NSLayoutConstraint!
var halfWidthConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
halfWidthConstraint = NSLayoutConstraint(item: fullWidthConstraint.firstItem,
attribute: fullWidthConstraint.firstAttribute,
relatedBy: fullWidthConstraint.relation,
toItem: fullWidthConstraint.secondItem,
attribute: fullWidthConstraint.secondAttribute,
multiplier: 0.5,
constant: fullWidthConstraint.constant)
halfWidthConstraint.priority = fullWidthConstraint.priority
}
@IBAction func changeConstraintAction(sender: UISwitch) {
if sender.on {
NSLayoutConstraint.deactivateConstraints([fullWidthConstraint])
NSLayoutConstraint.activateConstraints([halfWidthConstraint])
} else {
NSLayoutConstraint.deactivateConstraints([halfWidthConstraint])
NSLayoutConstraint.activateConstraints([fullWidthConstraint])
}
}
Run Code Online (Sandbox Code Playgroud)
在iOS 9+,Xcode 7+上测试过.
| 归档时间: |
|
| 查看次数: |
1676 次 |
| 最近记录: |