Dynamically resize height of a UICollectionViewCell with animation - ios

I'm looking to expand the height of the top cell in my collectionview with animation. The problem is when I detect a tap on the cell, I try animating the height and set the new height in the delegate: - collectionView:layout:sizeForItemAtIndexPath:indexPath. The issue I see an instant refresh after invalidating my collection flow layout and the animation happens afterwords. The effect I want is for the top cell to animate the expansion to the new height and push the rows beneath it along with the animation.
I'm only using one section with multiple rows. Should I try to use two sections and put the top cell in the first section and the remaining in the second section? Could I then animate the second section along with the height of the first section?

You need to do this three steps:
1.Invalidate your collectionViewLayout
self.collectionView.collectionViewLayout.invalidateLayout()
2.Reload desired indexPath or all the data inside a performBatchUpdates block
collectionView.performBatchUpdates({
self.collectionView.reload(at: DESIRED_INDEXPATH)
}, completion: nil)
3.Return the new height calculated in sizeForItemAtIndexpath delegate method

Related

How to change layout of a UITableViewCell with a UIStackView

I have a custom UITableViewCell with a vertical UIStackView. The stack view in-turn has 2 UILabels, one of it is hidden by default. How to change the height of the cell to show both labels in the stack view properly when the second label is unhidden. On a button click when i show the second label, it tries to show both label with the same height overlapping each other, however when i scroll the view up and down, it re-renders it ok.
I tried to call SizeToFit and LayoutIfNeeded with no help. How do i change the height of the row/cell to show both labels in the stackview to look proper?
You can call
tableView.beginUpdates()
tableVIew.endUpdates()
After tap on button, and your cell change height. It solution is compatible with animation.
On the button click, the label 2nd is showed, you should reload the table view, or reload exactly the cell, the height of cell will change and the cell will be re-rendered
Try reloading that row with reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) after you click the button that shows both labels.

How to animate UIStackView hiding inside UITableViewCell properly?

I want to animate the subviews of the TableViewCell which is StackView. When I hide the StackView, the TableViewCell height not updating. After googling, I found that I should call tableView.beginUpdates and tableView.endUpdates to notify tableView that there is a change in the cell. The problem is the hide animation and the change of tableview not sync.
Here is the view hierarchy for tableview cell
Content view - Container View (for card shadow) - Container Stack View - [Stack View for label and switch] & [StudentStackView for container of StudentView]
How can I sync the cell height and hide animation the correct way?
Here is the github repo: GitHub
Gif of the App:
You are right in using beginUpdates()/endUpdates(). Make sure you're not placing the someArrangedSubview.isHidden = true/false in an animate block since the table view and stack view will handle the animations accordingly. When the table view begins update operations, the stack view will resize any arranged subviews that you aren't removing to fill the entire space of the cell (even if you have height constraints on the arranged subview). In my case, the cell content jumped every time I wanted to collapse a cell via removing an arranged subview--so I added a dummy view between the view I wished to remain static* and the collapsible view. The static view won't resize, and the dummy view will expand/collapse as needed. Hope this helps.
*static in the sense that I didn't want the view to move when animating.
`public func setup(classRoom: ClassRoom, toggleInProcess: #escaping () -> (), toggled: #escaping () -> ()) {
containerStackView.addArrangedSubview(studentStackView)
self.nameLabel.text = classRoom.name
self.activeSwitch.isOn = classRoom.isActive
self.studentStackView.isHidden = !self.activeSwitch.isOn // Let him know his hide/unhide.
for student in classRoom.students {
let studentView = StudentView()
studentView.nameLabel.text = student.name
studentStackView.addArrangedSubview(studentView)
}
activeSwitch.addTarget(self, action: #selector(toggleShowStudents(show:)), for: .valueChanged)
self.toggleInProcess = toggleInProcess
self.toggled = toggled
setupShadow()
}`
` #objc func toggleShowStudents(show: Bool) {
UIView.animate(withDuration: 0.3, animations: {
self.studentStackView.isHidden = !self.activeSwitch.isOn
self.toggleInProcess()
self.containerView.layoutIfNeeded()
}) { _ in
self.toggled()
}
}`
your studentStackView also know his hide/unhide status while assigning values in function setup.
I left this as a comment but for anyone else experiencing this behavior, the root cause is the UILabel is expanding to fill the visible area before collapsing.
This can be fixed by doing the following 2 things:
Right below the UILabel, insert a Blank UIView
Adjust the Content Hugging Priority of the UILabel to "Required"
With these two adjustments, instead of the UILabel expanding to fill the visible area, the UIView expands instead. Visually, this appears as if the the cell just collapses.
tableView.beginUpdates and tableView.endUpdates are functions that should be called when you are about to modify rowcount or selected state of the rows.
You should try reloadData or reloadrowsatindexpaths, that should take care of the cell height adjustment.
You would better do it using performSelector API so as not to cause recursion in cellForRowAt call stack.

Auto set height of table view based on UICollectionView inside it

I have a UITableView with cells that have inside a UICollectionView.
Now all works great except of UICollectionViewCell scrolling i want that the height of table view cell follow the Collection view cell content.
In simple word i want scrolling in table view but not inside single cell i need to display all contents of UIcollectionViewCell without scrolling inside it.
Thanks
You have to calculate the collectionviews' heights and set a height constraint on each of them. then add top and bottom constraints from the collectionviews to their superviews (the tableviewcells / their contentviews) and let autolayout do its work.
don't forget
tableView.estimatedRowHeight = 44 // or something similar
tableView.rowHeight = UITableViewAutomaticDimension
in the controller's viewDidLoad to make the automatic row height calculation work.

How to make a UICollectionViewCell span entire row?

Context
I am trying to create something similar to a Table view using UICollectionView.
I am using Xcode7 and storyboarding.
The way I do it is that I drag the collection view across the entire controller view.
And then I drag the entire cell across the row and align it with the right and left boundaries.
Problem
But, when I place a label inside the cell, then it gets displayed correctly only when the device is in a horizontal position.
When the device is vertical, it gets cut off at the left boundary.
Question
How do I ensure that the width of the collection view cell matches that of the container width?
1) Implement the function of cell size and return the collection width:
-(CGSize) collectionView: (UICollectionView*) collectionView layout:(UICollectionViewLayout*) collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*) indexPath {
CGFloat height = 50; //set the wanted height
return CGSizeMake(collectionView.frame.size.width,height);
}
2) Reload the collection when the screen size change (i.e. orientation change).
It is because you are not using autolayout. You can achieve this entirely in storyboard or through code.
Using Storyboard
Add UICollectionView in your UIViewController in storyboard.
Drag UICollectionView to fill up in your UIViewController.
Add Constraints as shown in image.
Drag UICollectionView to fill up in UICollectionView.
Add UILabel (Or whatever you want to have in cell). Also add constraints in that element.
Build and run.

How to manually change UICollectionView height in Swift

I'm hiding rows that are completed in a collectionView.
I call cell.hidden = isCellHidden in cellForItemAtIndexPath when needed.
After I hide 10 rows there is plenty of empty space left and I'd like to trim down the size of the collectionView to only fit the rows that are not hidden.
The collectionView's design is kind of like a tableView.
I know with the tableView all I had to do to achieve this is set:
func section1VisibilityButton(sender: UIButton){
isCellHidden = !isCellHidden
self.tableView.reloadData()
self.tableView.contentSize.height = CGFloat(500)
}
with a collectionView when I try this it will resize it correctly but as soon as I try to scroll down it resizes itself back to the original height including the cells hidden (the cells layer is still hidden but there's tons of empty space bellow the last visible row as if they were visible)
For your issue, there are two options to change the frame of your collectionView/tableView.
If you are using autolayout, you need to create IBOutlet of bottom constraint or IBOutlet of constant height constraint of your tableView (anyone of these constraints, which you are using).
After reload tableView data you need to update constraint by calculating its height.
Suppose you are using constant height constraint and your calculated height is 150(e.g. 3 rows and 50 height of each row).
constraintTableViewHeight.constant = 150;//this will change height
self.view.layoutIfneed(); // this will apply updated constraints to whole view
If you are not using autolayout, you can manually change the height by changing tableView.frame property.

Resources