I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:
- (void)loadTweetWithId:(NSString *)tweetId {
if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
mTweetId = tweetId;
[[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
if (tweet) {
NSLog(#"Tweet loaded!");
[mTweetView configureWithTweet:tweet];
[mTweetView setShowActionButtons:YES];
//[mTweetView setDelegate:self];
[mTweetView setPresenterViewController:self.viewController];
[mTweetView setNeedsLayout];
[mTweetView layoutIfNeeded];
[mTweetView layoutSubviews];
hc.constant = mTweetView.frame.size.height;
[self updateConstraints];
[self layoutIfNeeded];
[self layoutSubviews];
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
[self.tableView layoutSubviews];
} else {
NSLog(#"Tweet load error: %#", [error localizedDescription]);
}
}];
}
}
When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?
UPDATE:
Using:
[self.tableView beginUpdates];
[self.tableView endUpdates];
is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.
UPDATE 2:
I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.
UPDATE 3:
I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.
While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.
Updated Answer:
You're doing a couple of things wrong that are likely to cause (or at least contribute to) the jumping:
Never call layoutSubviews yourself.
It's a method called by the system to resolve your constraints. It's automatically triggered when calling setNeedsLayout and layoutIfNeeded in a row.
The same applies to updateConstraints. It is called by the system during a layout pass. You can manually trigger it by subsequently calling setNeedsUpdateContraints and updateConstraintsIfNeeded. Furthermore, it only has an effect if you actually implemented (overrode) that method in your custom view (or cell).
When you call layoutIfNeeded on a view it layouts its subviews. Thus, when you change the constant of a constraint that constrains your mTweetView, it probably won't have any effect (unless the view hierarchy is invalidated during the triggered layout pass). You need to call layoutIfNeeded on mTweetView's superview which is the cell's content view (judging from the screenshot you added to your post):
[contentView layoutIfNeeded];
Furthermore, there is one more thing you need to be aware of that can cause flickering as well:
Cells in a table view are being recycled. Each time a cell is reused you load a new tweet. I guess it's from an asynchronous network request? If so, there is the possibility that the completion block from the first tweet you load for that cell instance returns after the completion block from the second tweet you load for that (recycled) cell when you scroll really fast or you internet connection is really slow. Make sure you cancel the request or invalidate it somehow when your cell is reused (prepareForReuse method).
Please make sure you've fixed all these issues and see if animation now works as expected. (My original answer below remains valid.)
Original Answer:
I'm pretty sure that
[self.tableView beginUpdates];
[self.tableView endUpdates];
is the only way to have a cell auto-resize itself while being displayed.
Reason:
For historic and performance reasons a UITableView always works with fixed-height cells (internally). Even when using self-sizing cells by setting an estimatedRowHeight etc. the table view will compute the height of a cell when it's dequeued, i.e. before it appears on screen. It will then add some internal constraints to the cell to give it a fixed width and a fixed height that just match the size computed by Auto Layout.
These internal constraints are only updated when needed, i.e. when a row is reloaded. Now when you add any constraints inside you cell you will "fight" against these internal constraints which have a required priority (aka 1000). In other words: There's no way to win!
The only way to update these internal (fixed) cell constraints is to tell the table view that it should. And as far as I know the only public (documented) API for that is
- (void)beginUpdates;
- (void)endUpdates;
So the only question that remains is:
Why is this approach not an option for you?
I think it's legitimate to redraw a cell after it's been resized. When you expand the cell to show a longer tweet than before the cell needs to be redrawn anyway!
You probably won't (and shouldn't) resize all visible cells all the time. (That would be quite confusing for the user...)
Try reloading that particular cell, after you loaded the tweet using,
- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation;
I had the similar issue and i got that fixed by adding all my code in dispatch_async to make sure its running on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
/*CODE HERE*/
});
So your code should be like this:
- (void)loadTweetWithId:(NSString *)tweetId {
if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
mTweetId = tweetId;
[[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (tweet) {
NSLog(#"Tweet loaded!");
[mTweetView configureWithTweet:tweet];
[mTweetView setShowActionButtons:YES];
//[mTweetView setDelegate:self];
[mTweetView setPresenterViewController:self.viewController];
[mTweetView setNeedsLayout];
[mTweetView layoutIfNeeded];
[mTweetView layoutSubviews];
hc.constant = mTweetView.frame.size.height;
[self updateConstraints];
[self layoutIfNeeded];
[self layoutSubviews];
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
[self.tableView layoutSubviews];
} else {
NSLog(#"Tweet load error: %#", [error localizedDescription]);
}
});
}];
}
}
Related
I'm facing this problem and I've been trying to figure out how to fix it but without success.
I have a table view with cells that contain an image which I still don't know which height is going to be. I created an outlet to the height constraint of the imageView and I'm downloading the image asynchronous with PinRemoteImage (I can use SDWebImage too but I think it's buggy in iOS 9). Inside the blocks is where I assign the new constant for the height constraint and then I do a layout update.
The cell never updates, the only way I can see the image correctly is scrolling down and then up (when the tableview repaints the cell)
__weak typeof(UITableView*) weakTable = tableView;
__weak typeof(NSIndexPath*) index = indexPath;
[cell.commentImageView pin_setImageFromURL:[[CTImageHelper sharedInstance] resizedImageURLConverterFromStringWithPrefix:comment.image.completePath andOptions:optionsString] completion:^(PINRemoteImageManagerResult *result) {
CommentTableViewCell *cellToUpdate = [weakTable cellForRowAtIndexPath:index];
cellToUpdate.heightSize = [NSNumber numberWithFloat:result.image.size.height/2];
cellToUpdate.commentImageViewHeightConstraint.constant = result.image.size.height/2;
[cellToUpdate setNeedsLayout];
}];
This is the code for setting the table view row height automatically
self.postTableView.estimatedRowHeight = 244.0;
self.postTableView.rowHeight = UITableViewAutomaticDimension;
And an image about the cell constraints:
Any ideas about what am I doing wrong? Thanks!
Put layoutIfNeeded just after setNeedsLayout
[cellToUpdate setNeedsLayout];
[cellToUpdate layoutIfNeeded];
// and then tell the tableView to update.
[weakTable beginUpdates];
[weakTable endUpdates];
// then scroll to the current indexPath
[weakTable scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionNone
animated:NO];
Update [weakTable beginUpdates];[weakTable endUpdates]; might crash if call it more than once at a time. you need to make sure there is no colision between them.
You may also try just reloading the cell itself.
[cellToUpdate setNeedsLayout];
[cellToUpdate layoutIfNeeded];
[weakTable reloadRowsAtIndexPaths:[indexPath] withRowAnimation:UITableViewRowAnimationNone];
You should call layoutIfNeeded after calling setNeedsLayout to actually trigger the layout.
You need to tell the tableview that the height has changed on it's cells by triggering an empty update, apart from the setNeedsLayout and layoutIfNeeded:
[tableView beginUpdates];
[tableView endUpdates];
I have a custom UITableViewCell with objects in it (such as UILabel, UITextView, UITextField etc.). When a button gets selected, a cell gets added to the tableView.
When I run it on the simulator, and the cell gets added, all the visible cell's and subviews height get really compact. (I do have auto constraint applied.)
....
[[self myTableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationTop];
If I do the following, the cells get back to normal:
NSArray* visibleCellIndex = self.myTableView.indexPathsForVisibleItems;
[self.myTableView reloadRowsAtIndexPaths:visibleCellIndex withRowAnimation:UITableViewRowAnimationFade];
[self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:savedScrollPosition inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
The problem with reloading the visible cells, is: First, that's a workaround, not getting to the source of the problem. Second, it's not a fully functioning workaround, because the whole tableView scrolls all the way up for a second, then scroll back to position.
The reason why it was shrinking, is because, you have to implement the method of heightForRowAtIndexPath.
The only problem now, is that the tableView jumps up, then scrolls to position. Don't know why.
Does your target run only on iOS 8 and later? If yes, you can set self.tableView.rowHeight = UITableViewAutomaticDimension to enable Autolayout for your cells. Then, you also don't need to implement delegate tableView:heightForRowAtIndexPath:.
If you're already doing this, your problem probably lies in your custom cell. Maybe its constraints are not well defined? How do you initialize the cell's constraints?
Another idea is to trigger the layout pass manually in tableView:cellForRowAtIndexPath:. After the cell has been initialized and its text label values have been set, call:
[cell setNeedsLayout];
[cell layoutIfNeeded];
I have a UICollectionView that gets updated like so:
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPaths:pathsRemoved];
[self.collectionView insertItemsAtIndexPaths:pathsAdded];
}
Usually, this works just fine, but under certain circumstances the data source count doesn't match the original number of items - count of pathsRemoved + count of pathsAdded.
Therefore, I wrapped this code inside a #try/#catch block that then calls [self.collectionView reloadData].
What ends up happening, however, is that after reloading the data, the layout becomes messed up; cells that were previously there (above on-screen cells, but off screen) no longer show. The collection view's content size is correct, and I can scroll up an down, but only see the cells that were on screen at time of reload.
Interestingly, Reveal.app shows that the other cells do in fact exist, but are hidden; I have a hunch that this is a red herring, and that there is some view caching going on here, but the cells are nonetheless listed in Reveal.
I have tried invalidating the layout, calling layoutIfNeeded, as well as the various subclass-of-flow-layout tricks I've found, and nothing has fixed it.
I've resorted to mitigating the issue by doing my own benign assertion, and doing a check to make sure the counts add up. If they do, performBatchUpdates. Else, don't bother, and just reload. This works, since we're bypassing performBatchUpdates: altogether. But I have to ask:
Is there a better way to gracefully recover from an assertion exception thrown from within performBatchUpdates:? Or is it that UICollectionViews are just buggy (still, on iOS 7).
I just find a way to handle this !
I tried like you to wrap the performBatchUpdates: code inside a #try/#catch block that calls [collectionView reloadData].
Then I realized that the problems disappeared when my ViewController was deallocated, the collectionView also.
So I found the ugly solution (but working) : kill your old collectionView and create a new one in the catch block.
#try {
[collectionView performBatchUpdates:^ {
// Do your stuff
}];
}
#catch (NSException *exception) {
UIView *oldSuperview = self.collectionView.superview;
[self.collectionView removeFromSuperview];
self.collectionView = [[UICollectionView alloc] initWithFrame:self.collectionView.frame collectionViewLayout:self.collectionView.collectionViewLayout];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
// set other collectionView's properties here
[oldSuperview addSubview:self.collectionView];
}
I know this is bad, but it saved me !
Does anyone know why contentSize is not updated immediately after reloadData is called on UICollectionView?
If you need to know the contentSize the best work around I've found is the following:
[_collectionView reloadData];
double delayInSeconds = 0.0001;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^(void)
{
// TODO: Whatever it is you want to do now that you know the contentSize.
});
Obviously this is a fairly brittle hack that makes assumptions on Apple's implementation but so far it has proven to work quite reliably.
Does anyone have any other workarounds or knowledge on why this happens? I'm debating submitting a radar because this I can't understand why they cannot calculate the contentSize in the same run loop. That is how UITableView has worked for its entire implementation.
EDIT: This question use to reference the setContentOffset method inside the block because I want to scroll the collection view in my app. I've removed the method call because peoples' answers focused on why wasn't I using scrollToItemAtIndexPath inside of why contentSize is not being updated.
To get the content size after reload, try to call collectionViewContentSize of the layout object. It works for me.
This worked for me:
[self.collectionView.collectionViewLayout invalidateLayout];
[self.collectionView.collectionViewLayout prepareLayout];
Edit: I've just tested this and indeed, when the data changes, my original solution will crash with the following:
"Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (7) must be equal to the number of items contained in that section before the update (100), plus or minus the number of items inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out)."
The right way to handle this is to calculate the insertions, deletions, and moves whenever the data source changes and to use performBatchUpdates around them when it does. For example, if two items are added to the end of an array which is the data source, this would be the code:
NSArray *indexPaths = #[indexPath1, indexPath2];
[self.collectionView performBatchUpdates:^()
{
[self.collectionView insertItemsAtIndexPaths:indexPaths];
} completion:^(BOOL finished) {
// TODO: Whatever it is you want to do now that you know the contentSize.
}];
Below is the edited solution of my original answer provided by Kernix which I don't think is guaranteed to work.
Try performBatchUpdates:completion: on UICollectionView. You should have access to the updated properties in the completion block. It would look like this:
[self.collectionView reloadData];
[self.collectionView performBatchUpdates:^()
{
} completion:^(BOOL finished) {
// TODO: Whatever it is you want to do now that you know the contentSize.
}];
After calling
[self.collectionView reloadData];
use this:
[self.collectionView setNeedsLayout];
[self.collectionView layoutIfNeeded];
then you can get the real contentSize
Call prepareLayout first, and then you will get correct contentSize:
[self.collectionView.collectionViewLayout prepareLayout];
In my case, I had a custom layout class that inherits UICollectionViewFlowLayout and set it only in the Interface Builder. I accidentally removed the class from the project but Xcode didn't give me any error, and the contentSize of the collection view returned always zero.
I put back the class and it started working again.
In my Project I use UICollectionView to display a grid of icons.
The user is able to change the ordering by clicking a segmented control which calling a fetch from core data with different NSSortDescriptor.
The amount of data is always the same, just ending up in different sections / rows:
- (IBAction)sortSegmentedControlChanged:(id)sender {
_fetchedResultsController = nil;
_fetchedResultsController = [self newFetchResultsControllerForSort];
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
[self.collectionView reloadData];
}
The problem is that reloadData doesn't animate the change, UICollectionView just pops with the new data.
Should I keep track in which indexPath a cell was before and after change, and use [self.collectionView moveItemAtIndexPath: toIndexPath:] to perform the animation for the change or there is a better method ?
I didn't get much into subclassing collectionViews so any help will be great...
Thanks,
Bill.
Wrapping -reloadData in -performBatchUpdates: does not seem to cause a one-section collection view to animate.
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadData];
} completion:nil];
However, this code works:
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
} completion:nil];
reloadData doesn't animate, nor does it reliabably do so when put in a UIView animation block. It wants to be in a UICollecitonView performBatchUpdates block, so try something more like:
[self.collectionView performBatchUpdates:^{
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
} completion:^(BOOL finished) {
// do something on completion
}];
This is what I did to animate reload of ALL SECTIONS:
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.collectionView.numberOfSections)]];
Swift 3
let range = Range(uncheckedBounds: (0, collectionView.numberOfSections))
let indexSet = IndexSet(integersIn: range)
collectionView.reloadSections(indexSet)
For Swift users, if your collectionview only has one section:
self.collectionView.performBatchUpdates({
let indexSet = IndexSet(integersIn: 0...0)
self.collectionView.reloadSections(indexSet)
}, completion: nil)
As seen on https://stackoverflow.com/a/42001389/4455570
Reloading the whole collection view inside a performBatchUpdates:completion: block does a glitchy animation for me on iOS 9 simulator. If you have a specific UICollectionViewCell you want do delete, or if you have it's index path, you could call deleteItemsAtIndexPaths: in that block. By using deleteItemsAtIndexPaths:, it does a smooth and nice animation.
UICollectionViewCell* cellToDelete = /* ... */;
NSIndexPath* indexPathToDelete = /* ... */;
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPaths:#[[self.collectionView indexPathForCell:cell]]];
// or...
[self.collectionView deleteItemsAtIndexPaths:#[indexPath]];
} completion:nil];
The help text says:
Call this method to reload all of the items in the collection view.
This causes the collection view to discard any currently visible items
and redisplay them. For efficiency, the collection view only displays
those cells and supplementary views that are visible. If the
collection data shrinks as a result of the reload, the collection view
adjusts its scrolling offsets accordingly. You should not call this
method in the middle of animation blocks where items are being
inserted or deleted. Insertions and deletions automatically cause the
table’s data to be updated appropriately.
I think the key part is "causes the collection view to discard any currently visible items". How is it going to animate the movement of items it has discarded?