英文:
Expanding UIView with Auto Layout Constraint Not Working Properly
问题
我有一个名为UpperInformationUIView的自定义UIView类,我试图根据不同的状态(默认、收缩和展开)来展开和折叠它。折叠功能似乎正常工作,但是当我尝试展开视图时遇到了问题。
这是我的代码片段:
private func expandView() {
switch viewHeightState {
case .defaulted:
viewHeightConstraint.constant = maxHeight
viewHeightState = .expanded
case .shrinked:
viewHeightConstraint.constant = defaultHeight
viewHeightState = .defaulted
case .expanded:
return // 已经展开了
}
UIView.animate(withDuration: 2) {
self.layoutIfNeeded()
}
}
我希望视图根据当前状态从当前状态扩展到maxHeight或defaultHeight。但是视图的中心位置首先向下移动,然后在垂直方向上拉伸,而不是像预期的那样仅向下展开。
我还在Storyboard中将顶部空间约束设置为0,但问题仍然存在。
请问有人可以指导我找出我漏掉了什么或出了什么问题吗?谢谢!
英文:
I have a custom UIView class named UpperInformationUIView, and I'm trying to expand and collapse it based on different states (default, shrinked, and expanded). The collapse function seems to be working fine, but I'm facing an issue when trying to expand the view.
Here's my code snippet:
private func expandView() {
switch viewHeightState {
case .defaulted:
viewHeightConstraint.constant = maxHeight
viewHeightState = .expanded
case .shrinked:
viewHeightConstraint.constant = defaultHeight
viewHeightState = .defaulted
case .expanded:
return // Already expanded
}
UIView.animate(withDuration: 2) {
self.layoutIfNeeded()
}
}
I want the view to expand from the current state to either maxHeight or defaultHeight, depending on the current state. But the view's center position is moving to the bottom first, and then it is stretching vertically, instead of only expanding downward as intended.
I've also set the top space constraint to 0 in the storyboard, but the problem persists.
Could anyone please guide me to find what I'm missing or what's going wrong? Thank you!
答案1
得分: 0
你的代码没问题,只是忘记提到parrentView
。只需修改self.layoutIfNeeded()
,将其替换为self.superview.layoutIfNeeded()
,希望这样能解决问题。如果你再次遇到问题,请提及具体情况。
英文:
Your Code is Fine . you just forgot to mention yoit parrentView .
Just modify your self.layoutIfNeeded()
and replace it by self. self.superview.layoutIfNeeded()
hope it will work .
if you face issue again please mention then .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论