我有一个带有 AutoLayout 的视图,它适用于不同的屏幕尺寸.屏幕上有一个元素,但它会根据用户操作四处移动.每当我向下导航到另一个屏幕然后返回此视图时,此元素都会重置为其原始位置.
I have a view with AutoLayout and it works nicely with different screen sizes. There's one element on the screen though that moves around depending on user actions. Whenever I navigate down to a different screen then back to this view, this element gets reset to its original position.
我明白为什么会发生这种情况,但我该如何预防呢?我确实希望它最初设置正确,但不是在第一次之后.
I understand why this happens but how can I prevent it? I do want it to be setup correctly initially but not after the first time.
如果你使用 Autolayout,你永远不应该使用 setFrame/setBounds,因为你已经看到 Autolayout 会忽略它们并在更新时重写它们.
If you're using Autolayout you should never use setFrame/setBounds because as you've seen Autolayout ignores them and rewrites them when it updates.
解决办法是改变约束.约束有一个名为 constant
的参数,这是创建约束后唯一可以更改的参数.当您需要移动 NSViews 时,您还可以添加/删除额外的约束.
The solution is to change the constraints. A constraint has a parameter called constant
which is the only thing you can change on a constraint after it has been created. You can also add/remove extra constraints when you need to move NSViews around.
WWDC 2012 上有一个视频,其中有一个非常好的示例,说明如何使用 AutoLayout 移动视图.
There is a video from WWDC 2012 that had a very good example of how to move views with AutoLayout.
这篇关于如何防止 AutoLayout 重置视图框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!