在Swift中运行时更改受自动布局约束的UIView的框架 [英] Changing an Autolayout-constrained UIView's frame at runtime in Swift
问题描述
例如,我使用此代码来更改名为Propo
的UIView
的帧位置:
For example, I use this code to change the frame position of a UIView
called Propo
:
self.Propo.frame.origin.x -= self.view.frame.width
(Propo
在分镜脚本中有约束)
(Propo
has constraints in Storyboard)
但是,当应用视图消失并重新出现时,UIView
会将其自身重置为其原始位置.我该如何解决?我希望通过编程方式更改UIView
的位置.
But When the app view disappears and reappears, the UIView
resets itself to its original position. How can I do to resolve it? I want the UIView
to keep its position when I change it programmatically.
我尝试用updateViewConstraints()
进行其他操作追加...
I've tried updateViewConstraints()
by anything else append...
推荐答案
约束和手动框架操作直接冲突.您必须选择一个.相反,您应通过故事板中的@IBOutlet将Ctrl拖动到您的视图控制器上,来提升"您想要更改的约束.然后,您可以操纵其常量:
Constraints and manual frame manipulation are directly in conflict. You have to choose one or the other. You should instead "promote" the constraint you wish to change by Ctrl-dragging it to your view controller as an @IBOutlet in Storyboard. Then, you can manipulate its constant:
class MyViewController: UIViewController {
@IBOutlet weak var myPropoLeftEdgeConstraint: NSLayoutConstraint!
@IBAction doChangePropo(sender: AnyObject) {
myPropoLeftEdgeConstraint.constant -= view.frame.width
view.layoutIfNeeded()
}
}
许多地方的目标C中已经涵盖了这一点,因此,如果您可以阅读这些示例,则只需进行搜索即可以编程方式更改代码中的NSLayoutConstraint.
This is already covered in Objective C in many places, so just do a search on programmatically changing an NSLayoutConstraint in code if you can read those examples.
(进行编辑以使其更加适用:通常应该对约束进行动画处理,以获得干净的用户体验.否则,眼睛会感到困惑.)
(Edit to make more applicable: generally constraints should be animated for a clean user experience. Otherwise the eye is confused.)
通过将view.layoutIfneeded
包装在UIView.animateWithDuration(duration) { ... }
块中,可以轻松地为约束调整设置动画.
You can easily animate the constraint adjustment by wrapping view.layoutIfneeded
in a UIView.animateWithDuration(duration) { ... }
block.
这篇关于在Swift中运行时更改受自动布局约束的UIView的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!