当按下 UIBarButton 时,UIView 会回到原来的框架
UIView snaps back to original frame when UIBarButton is pressed
在名为 "courseView" 的 UIView 顶部,我有一个带有栏按钮的工具栏,名为 "expand button"。当我按下该按钮时,会调用 expandCourseView() 并且视图框架会正确设置动画。但是,在动画完成后,我希望 "expandButton" 更改文本。当它执行此操作时,视图的框架会自动恢复到其原始形状。为什么会这样?好像工具栏上的按钮没有记录它的位置已经移动。
@IBOutlet weak var expandButton: UIBarButtonItem!
@IBAction func expandButton(sender: AnyObject) {
expandCourseView()
}
func expandCourseView(){
let width = self.courseView.frame.width
let height = self.courseView.frame.height
let frameOffset : CGFloat = 200
UIView.animateWithDuration(0.5, animations: { () -> Void in
if (height < 211){
self.courseView.frame = CGRect(x: self.courseView.frame.minX, y: self.courseView.frame.minY - frameOffset, width: width, height: height + frameOffset)
}
else {
self.courseView.frame = CGRect(x: self.courseView.frame.minX, y: self.courseView.frame.minY + frameOffset, width: width, height: height - frameOffset)
}
}) { (value: Bool) -> Void in
if height < 211{
self.expandButton.title = "Close"
} else {
self.expandButton.title = "Expand"
}
}
}
您可能正在使用自动布局。尽管您可以直接操作帧来为视图设置动画或移动视图,但在某些时候(例如设置标签的文本值)会调用 setNeedsLayout()
并导致视图恢复为约束指定的值。
您可以离开动画 as-is,但在完成时(或在 updateConstraints()
中)您需要修改约束以将视图保持在新位置。
在名为 "courseView" 的 UIView 顶部,我有一个带有栏按钮的工具栏,名为 "expand button"。当我按下该按钮时,会调用 expandCourseView() 并且视图框架会正确设置动画。但是,在动画完成后,我希望 "expandButton" 更改文本。当它执行此操作时,视图的框架会自动恢复到其原始形状。为什么会这样?好像工具栏上的按钮没有记录它的位置已经移动。
@IBOutlet weak var expandButton: UIBarButtonItem!
@IBAction func expandButton(sender: AnyObject) {
expandCourseView()
}
func expandCourseView(){
let width = self.courseView.frame.width
let height = self.courseView.frame.height
let frameOffset : CGFloat = 200
UIView.animateWithDuration(0.5, animations: { () -> Void in
if (height < 211){
self.courseView.frame = CGRect(x: self.courseView.frame.minX, y: self.courseView.frame.minY - frameOffset, width: width, height: height + frameOffset)
}
else {
self.courseView.frame = CGRect(x: self.courseView.frame.minX, y: self.courseView.frame.minY + frameOffset, width: width, height: height - frameOffset)
}
}) { (value: Bool) -> Void in
if height < 211{
self.expandButton.title = "Close"
} else {
self.expandButton.title = "Expand"
}
}
}
您可能正在使用自动布局。尽管您可以直接操作帧来为视图设置动画或移动视图,但在某些时候(例如设置标签的文本值)会调用 setNeedsLayout()
并导致视图恢复为约束指定的值。
您可以离开动画 as-is,但在完成时(或在 updateConstraints()
中)您需要修改约束以将视图保持在新位置。