I have expandable UILabel:
func expandDescriptionLabel() {
let calculatedHeightDescriptionLabel = lblDescription.sizeThatFits(CGSizeMake(lblDescription.frame.width, CGFloat.max)).height
expanded = true
UIView.animateWithDuration(0.3, animations: {
self.cnsDescriptionHeight.constant = calculatedHeightDescriptionLabel
self.hideMoreButton()// this line means nothing, results are the same with this line commented out
self.view.layoutIfNeeded()
})
}
func reduceDescriptionLabel() {
expanded = false
self.cnsDescriptionHeight.constant = 60
UIView.animateWithDuration(0.3, animations: {
self.showMoreButton() // this line means nothing, results are the same with this line commented out
self.lblDescription.setNeedsLayout();
self.view.layoutIfNeeded()
})
}
When expanding animation looks just fine, but when height is decreasing strange things happen. Look at GIF below. I tried already CGAffineTransformScale and putting UILabel in UIView and then animating a UIView.
Question is how to make the last part of animation more smooth.
As you can see when Labels height is decreasing, text is moving up and then suddenly appear in correct place(without animation).
Related
I have a Header view that contains pager view (FSPagerView), which has an item (FSPagerViewCell) that contains bar chart, 2019, year review texts. I'm trying to scale down Header at certain times with such code:
private func setSelfHeightAnimated(height: CGFloat)
{
UIView.animate(withDuration: 0.2, animations: {
self.selfHeightAnchor.constant = height
self.superview?.layoutIfNeeded()
})
}
private func setPagerHeightAnimated(height: CGFloat)
{
UIView.animate(withDuration: 0.2, animations: {
self.pagerHeightAnchor.constant = height
self.layoutIfNeeded()
// self.pagerView.layoutIfNeeded()
// self.pagerView.layoutSubviews()
// self.pagerView.cellForItem(at: 0)?.layoutIfNeeded()
// self.pagerView.cellForItem(at: 0)?.setNeedsDisplay()
// self.superview?.layoutIfNeeded()
// self.setNeedsDisplay()
// self.pagerView.setNeedsDisplay()
})
}
However, the old frame glitch is very visible. What could be missing? Here is the video: https://streamable.com/owsdi
You have an 1st layout and a 2nd layout, and an animation that leads from the 1st to the 2nd.
Currently, the 1st layout is faded out and the 2nd layout is faded in during the animation, which gives you the „glitch“.
I assume what you want to achieve is:
- The top part (History, 2019, Year review) should keep their height, and
- only the columns below should shrink/expand, while the lower table slides up or down.
A solution probably is that you animate only the height of a subview that contains the 2 columns.
If the header view is set to adopt its height to its contents, then I expect that the required effect is shown without a glitch.
EDIT:
If you definitively had to animate the upper part as a whole, one possibility may be (that I consider as ugly) to set the alpha value of History, 2019, and Year to 0 immediately before the animation begins. Then these texts would only fade in so the glitch with double images at different places would be avoided.
Try like this to avoid glitching.
private func setSelfHeightAnimated(height: CGFloat)
{
self.selfHeightAnchor.constant = height
UIView.animate(withDuration: 0.2, animations: {
self.layoutIfNeeded()
self.viewDidLayoutSubviews()
})
}
private func setPagerHeightAnimated(height: CGFloat)
{
self.pagerHeightAnchor.constant = height
UIView.animate(withDuration: 0.2, animations: {
self.layoutIfNeeded()
self.viewDidLayoutSubviews()
})
}
I have a UILabel inside a UIStackView, and the stack view is inside another UIScrollView, I'm using auto layout. The label has single line (ie. numberOfLines equal to 1) and in a few cases I need to set it to multiline (ie. numberOfLines equal to 0) with an animation that expands it.
func expand() {
label.numberOfLines = 0
}
when I click expand:
messageView.expand()
UIView.animate(withDuration: 0.3) {
self.layoutIfNeeded()
}
However, when it expands, the label's frame isn't updated and I have to scroll (the scroll view) to make it fully visible. What could be wrong?
Thanks!
Have you changed the label's text?
Check if the autolayout is correct
Animation of UILabel doesn't perform within
UIView.animate(withDuration:).
This should work:
UIView.transition(with: label, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.label.numberOfLines = 0
})
You can experiment with options and execution block.
I have a simple UI (very similar to Uber) where the user can scroll a table view on top of the main content.
The UI and the corresponding UITableView animation bug can be displayed as:
Here is what is happening:
User taps on the table view and the table view is expanded. This is done via adding the layout constraint that makes sure that tableView.top = topMenu.bottom. The constraint that gets removed is tableView.height = 30. Everything looks good.
User then scrolls down a certain amount (55+ pixels) and the constraints are reverted back to their original states. This happens inside an animation block so that the flow looks smooth.
The bug occurs here. As far as I understand, the tableView's visible area is calculated of how it will look like after the animation ends. However, this calculation happens before the animation. Therefore, during the animation only 1-2 cells are displayed on the table view; causing the bug.
I can have a workaround here by temporarily setting the tableView's height to a large value and only setting it back to a small value after the animation ends. However, that doesn't work because the safe area on iPhoneX gets covered by the tableView.
Relevant code is here:
private func animateTheChange() {
UIView.animate(withDuration: 0.8, animations: {
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
})
}
override func updateViewConstraints() {
self.touchConstraints()
super.updateViewConstraints()
}
private func touchConstraints() {
if self.collapsed {
self.view.addConstraint(self.collapsedConstraint)
self.view.removeConstraint(self.expandedConstraint)
if UserHardware.IS_IPHONE_X {
self.bottomConstraint.constant = 0
}
}
else { // Expand
self.view.addConstraint(self.expandedConstraint)
self.view.removeConstraint(self.collapsedConstraint)
if UserHardware.IS_IPHONE_X {
self.bottomConstraint.constant = 34
}
}
}
Relevant Stackoverflow questions (that help but don't solve the issue):
UITableView frame height animation glitch
Dynamic UITableView height
UITableView frame change animation issue
One option...
Embed your tableView inside a "containing" UIView
Constrain the tableView to Top and Bottom of the containing view
Constrain the containing view Bottom to the Safe Area Bottom
Constrain the containing view Top to the Bottom of topMenu with a Priority of 250 (default low), and connect it to #IBOutlet var tableContainerTop: NSLayoutConstraint!
Constrain the Height of the containing view to 30 with a Priority of 750 (default high), and connect it to #IBOutlet var tableContainerHeight: NSLayoutConstraint!
When you want to "expand" or "collapse" your tableView, change the priorities of the containing view's constraints.
UIView.animate(withDuration: 0.8, animations: {
if self.isExpanded {
self.tableContainerHeight.priority = .defaultHigh
self.tableContainerTop.priority = .defaultLow
} else {
self.tableContainerHeight.priority = .defaultLow
self.tableContainerTop.priority = .defaultHigh
}
self.view.layoutIfNeeded()
})
I have a viewcontroller with 3 UIViews that are stacked on top of each other. By stacked I mean at the bottom of one view, the next view begins. I have placed vertical constraints between each view with constant = 0. When the application begins, in viewDidLoad, I'm adding 500 to the vertical constraint between the two top views, so the bottom two views are pushed down below by doing:
billViewBottomConstraint.constant = 500
I then call the following function to animate the two bottom views moving back up, ending right below the top view:
func animate()
{
self.billViewBottomConstraint.constant = 0
UIView.animate(withDuration: 2.0) {
self.view.layoutIfNeeded()
}
}
The views certainly animate to the right position, but not the way I want. It looks like before the views animate, they are expanded outwards and when the animation is called they contract up and inwards towards the right position.
Inside viewDidLoad, the layout is not ready to be animated. You should wait at least until viewDidLayoutSubviews to properly animate constraints. Check with a boolean to make sure it runs only for the first time.
fileprivate var firstLayoutSubviewsTime = true
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if firstLayoutSubviewsTime {
firstLayoutSubviewsTime = false
animate()
}
}
You should call view.layoutIfNeeded() before the animation block to make sure all views are loaded properly.
You should also modify the constant inside the animation block, not before it.
func animate() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 2.0) {
self.billViewBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
I'm experiencing a glitch where my UITextField's text jumps to its final position (it doesn't animate) when animating the textfield's width constraint. Take a look at this gif:
When the "Grow" button is tapped, the textfield's width grows. But "hello world" jumps immediately to the center instead of gliding there. When the "Shrink" button is tapped, "hello world" jumps immediately back to the left.
My animation function looks like this:
func animateGrowShrinkTextFields(grow: Bool) {
if grow {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 330
self.view.layoutIfNeeded()
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 100
self.view.layoutIfNeeded()
}, completion: nil)
}
}
I have tried the following list suggestions; none of them worked.
I called self.view.layoutIfNeeded() and self.helloWorldTextField.layoutIfNeeded() before and within the animation block as suggested in this answer: https://stackoverflow.com/a/32996503/2179970
I tried self.view.layoutSubviews and self.helloWorldTextField.layoutSubview as suggested in this answer: https://stackoverflow.com/a/30845306/2179970
Also tried setNeedsLayout() UITextField text jumps iOS 9
I even tried changing the font as suggested here: https://stackoverflow.com/a/35681037/2179970
I tried resignFirstResponder (although though I never tap or edit the textfield in my tests, so it should not involve the firstResponder) as suggested here: https://stackoverflow.com/a/33334567/2179970
I tried subclassing UITextField as seen here: https://stackoverflow.com/a/40279630/2179970
I also tried using a UILabel and got the same jumpy result.
The following question is also very similar to mine but does not have an answer yet: UITextfield text position not animating while width constraint is animated
Here is my project on Github: https://github.com/starkindustries/ConstraintAnimationTest
Solution Demo
I've found a working solution. It feels a little hackish but it works. Here is a gif of the final result. Notice that helloWorldTextField has a blue border to show its location within the second textfield behind it.
Instructions
Make two textfields: helloWorldTextField (the original from the question) and borderTextField (a new textfield). Remove helloWorldTextFields's border and background color. Keep borderTextField's border and background color. Center helloWorldTextField within borderTextField. Then animate the width of borderTextField.
Github link and Code
Here is the project on Github: https://github.com/starkindustries/ConstraintAnimationTest
Here is the code within MyViewController class. Everything else is setup in the storyboard which can be viewed on Github at the link above.
class MyViewController: UIViewController {
// Hello World TextField Border var
#IBOutlet weak var borderTextFieldWidth: NSLayoutConstraint!
// Button Vars
#IBOutlet weak var myButton: UIButton!
var grow: Bool = false
func animateGrowShrinkTextFields(grow: Bool, duration: TimeInterval) {
if grow {
UIView.animate(withDuration: duration, animations: {
self.borderTextFieldWidth.constant = 330
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
print("Grow animation complete!")
})
} else {
UIView.animate(withDuration: duration, animations: {
self.borderTextFieldWidth.constant = 115
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
print("Shrink animation complete!")
})
}
}
#IBAction func toggle(){
let duration: TimeInterval = 1.0
grow = !grow
let title = grow ? "Shrink" : "Grow"
myButton.setTitle(title, for: UIControlState.normal)
animateGrowShrinkTextFields(grow: grow, duration: duration)
}
}
Notes and References
What led me to this solution was #JimmyJames's comment: "You are just animating the UITextField width, but the content inside is not animated."
I researched how to animate font changes and came across this question: Is there a way to animate changing a UILabel's textAlignment?
In that question #CSmith mentioned that "you can animate the FRAME, not the textAlignment" https://stackoverflow.com/a/19251634/2179970
The accepted answer in that question suggests to use a UILabel within another frame. https://stackoverflow.com/a/19251735/2179970
Hope this helps anyone else who comes across this problem. If anyone has another way to solve this, please post a comment or another answer. Thanks!
Another solution for the issue is set yourLabel.contentMode = .center on init, and animate in animation block as usually