Description
New Issue Checklist
- I have looked at the DocumentationI have read the F.A.Q.
Issue Info
Info | Value |
---|---|
Platform | ios |
Platform Version | 9.3 |
SnapKit Version | 0.20.0 |
Integration Method | cocoapods |
Issue Description
UILabel constraints seem to break when animating the width getting smaller
.
The Setup
In my UIViewController I have 3 UIViews, stacked horizontally:
Box1 - Box2 - Box3
Box1 and Box3 have a specific size, and Box2 fills up the remaining space between them.
I also have a UILabel, centred at the middle of the screen, and with its size depending on the size of Box2.
// The UIView
box2.snp_makeConstraints { (make) in
make.leading.equalTo(box1.snp_trailing)
make.trailing.equalTo(box3.snp_leading)
make.top.equalTo(box1.snp_top)
make.bottom.equalTo(box1.snp_bottom)
}
// The label
centerLabel.snp_makeConstraints { (make) in
make.center.equalTo(self.view.snp_center).priorityRequired()
make.size.equalTo(box2.snp_size)
}
I have a button that calls a toggle function. Either Box1 and Box3 get larger, thus shrinking Box2. Or Box1 and Box3 get smaller, thus expanding Box2.
The Label's size changes accordingly with Box2 and works perfectly well when Box2 is expanding.
The issue is when Box2 is shrinking: the label shrinks right away (not animated) and aligns with the left border of Box2 rather than staying centred.
// This is the toggle function
func changeConstraints(){
self.box1.snp_updateConstraints(closure: { (make) in
make.width.equalTo(CGRectGetWidth(self.box1.frame) == 50 ? 100 : 50)
})
self.box3.snp_updateConstraints(closure: { (make) in
make.width.equalTo(CGRectGetWidth(self.box3.frame) == 50 ? 100 : 50)
})
UIView.animateWithDuration(1.2, animations: {
self.view.layoutIfNeeded()
})
}
Any idea what's causing this? Am I overlooking something?
Activity
robertjpayne commentedon Apr 6, 2016
@Audioy just looks like the label isn't getting captured in the animation block, can you make sure you invalidate it's layout before calling self.view.layoutIfNeeded()?
Such as:
Erkened commentedon Apr 6, 2016
Thanks @robertjpayne Just followed your advice, but no better luck unfortunately.
robertjpayne commentedon Apr 9, 2016
@Audioy unfortunately then I think this is just how UIKit works :( I think I've seen this too it sort of calculates the final layout of the label glyphs and doesn't really animate in between...
What wrapping mode do you have on the label? It might work if it was set to truncate
Erkened commentedon Apr 11, 2016
@robertjpayne I think you're right in that it's how UIKit works. I've tried all the wrapping mode available but to no avail. Oh well. I guess I'll just add the label to a UIView so that the animation remains smooth. Thanks!
lsamaria commentedon May 18, 2021
I had the same exact issue. I found the answer here
You have to set the
contentMode
for your labelfor example if my
textAlignment
was.center
:myLabel.textAlignment = .center
then the
contentMode
would be:myLabel.contentMode = .center