Consider a UICollectionView with flow layout and horizontal direction. By default, cells are ordered from top to bottom, left to right. Like this:
1 4 7 10 13 16
2 5 8 11 14 17
3 6 9 12 15 18
In my case, the collection view is paged and it has been designed so that a specific number of cells fits in each page. Thus, a more natural ordering would be:
1 2 3 10 11 12
4 5 6 - 13 14 15
7 8 9 16 17 18
What would be the simplest to achieve this, short of implementing my own custom layout? In particular, I don't want to loose any of the functionalities that come for free with UICollectionViewFlowLayout (such as insert/remove animations).
Or in general, how do you implement a reordering function f(n) on a flow layout? The same could be applicable to a right-to-left ordering, for example.
My approach so far
My first approach was to subclass UICollectionViewFlowLayout and override layoutAttributesForItemAtIndexPath::
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *reorderedIndexPath = [self reorderedIndexPathOfIndexPath:indexPath];
UICollectionViewLayoutAttributes *layout = [super layoutAttributesForItemAtIndexPath:reorderedIndexPath];
layout.indexPath = indexPath;
return layout;
}
Where reorderedIndexPathOfIndexPath: is f(n). By calling super, I don't have to calculate the layout of each element manually.
Additionally, I had to override layoutAttributesForElementsInRect:, which is the method the layout uses to choose which elements to display.
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *result = [NSMutableArray array];
NSInteger sectionCount = 1;
if ([self.collectionView.dataSource respondsToSelector:#selector(numberOfSectionsInCollectionView:)])
{
sectionCount = [self.collectionView.dataSource numberOfSectionsInCollectionView:self.collectionView];
}
for (int s = 0; s < sectionCount; s++)
{
NSInteger itemCount = [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:s];
for (int i = 0; i < itemCount; i++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:s];
UICollectionViewLayoutAttributes *layout = [self layoutAttributesForItemAtIndexPath:indexPath];
if (CGRectIntersectsRect(rect, layout.frame))
{
[result addObject:layout];
}
}
}
return result;
}
Here I just try every element and if it is within the given rect, I return it.
If this approach is the way to go, I have the following more specific questions:
Is there any way I can simplify the layoutAttributesForElementsInRect: override, or make it more efficient?
Am I missing something? At the very least swapping cells of different pages produces odd results. I suspect it's related to initialLayoutAttributesForAppearingItemAtIndexPath: and finalLayoutAttributesForDisappearingItemAtIndexPath:, but I can't pinpoint exactly what is the problem.
In my case, f(n) depends on the number of columns and rows of each page. Is there any way of extracting this information from UICollectionViewFlowLayout, short of hardcoding it myself? I thought of querying layoutAttributesForElementsInRect: with the bounds of the collection view, and deducing the rows and columns from there, but this also feels inefficient.
I've thought a lot about your question and came to following considerations:
Subclassing the FlowLayout seems to be the rightest and the most effective way to reorder cells and to make use of flow layout animations. And your approach works, except of two important things:
Let's say you have a collection view with only 2 cells and you have designed your page so that it can contain 9 cells. First cell will be positioned at the top left corner of the view, like in original flow layout. Your second cell, however, should be positioned at the top of the view and it has an index path [0, 1]. The reordered index path would be [0, 3] (index path of original flow layout cell that would be on its place). And in your layoutAttributesForItemAtIndexPath override you would send the message like [super layoutAttributesForItemAtIndexPath:[0, 3]], you would get an nil object, just because there are only 2 cells: [0,0] and [0,1]. And this would be the problem for your last page.
Even though you can implement the paging behavior by overriding targetContentOffsetForProposedContentOffset:withScrollingVelocity: and manually set properties like itemSize, minimumLineSpacing and minimumInteritemSpacing, it's much work to make your items be symmetrical, to define the paging borders and so on.
I thnik, subclassing the flow layout is preparing much implementation for you, because what you want is not a flow layout anymore. But let's think about it together.
Regarding your questions:
your layoutAttributesForElementsInRect: override is exactly how the original apple implementation is, so there is no way to simplify it. For your case though, you could consider following: if you have 3 rows of items per page, and the frame of item in first row intersects the rect frame, then (if all items have same size) the frames of second and third row items intersect this rect.
sorry, I didn't understand your second question
in my case the reordering function looks like this: (a is the integer number of rows/columns on every page, rows=columns)
f(n) = (n % a²) + (a - 1)(col - row) + a²(n / a²); col = (n % a²) % a; row = (n % a²) / a;
Answering the question, the flow layout has no idea how many rows are in each column because this number can vary from column to column depending on size of every item. It can also say nothing about number of columns on each page because it depends on the scrolling position and can also vary. So there is no better way than querying layoutAttributesForElementsInRect, but this will include also cells, that are only partically visible. Since your cells are equal in size, you could theoretically find out how many rows has your collection view with horizontal scrolling direction: by starting iterating each cell counting them and breaking if their frame.origin.x changes.
So, I think, you have two options to achieve your purpose:
Subclass UICollectionViewLayout. It seems to be much work implementing all those methods, but it's the only effective way. You could have for example properties like itemSize, itemsInOneRow. Then you could easily find a formula to calculate the frame of each item based on it's number (the best way is to do it in prepareLayout and store all frames in array, so that you cann access the frame you need in layoutAttributesForItemAtIndexPath). Implementing layoutAttributesForItemAtIndexPath, layoutAttributesForItemsInRect and collectionViewContentSize would be very simple as well. In initialLayoutAttributesForAppearingItemAtIndexPath and finalLayoutAttributesForDisappearingItemAtIndexPath you could just set the alpha attribute to 0.0. That's how standard flow layout animations work. By overriding targetContentOffsetForProposedContentOffset:withScrollingVelocity: you could implement the "paging behavior".
Consider making a collection view with flow layout, pagingEnabled = YES, horizontal scrolling direction and item size equal to screen size. One item per screen size. To each cell you could set a new collection view as subview with vertical flow layout and the same data source as other collection views but with an offset. It's very efficient, because then you reuse whole collection views containing blocks of 9 (or whatever) cells instead of reusing each cell with standard approach. All animations should work properly.
Here you can download a sample project using the layout subclassing approach. (#2)
Wouldn't it be a simple solution to have 2 collection views with standart UICollectionViewFlowLayout?
Or even better: to have a page view controller with horizontal scrolling, and each page would be a collection view with normal flow layout.
The idea is following: in your UICollectionViewController -init method you create a second collection view with frame offset to the right by your original collection view width. Then you add it as subview to original collection view. To switch between collection views, just add a swipe recognizer. To calculate offset values you can store the original frame of collection view in ivar cVFrame. To identify your collection views you can use tags.
Example of init method:
CGRect cVFrame = self.collectionView.frame;
UICollectionView *secondView = [[UICollectionView alloc]
initWithFrame:CGRectMake(cVFrame.origin.x + cVFrame.size.width, 0,
cVFrame.size.width, cVFrame.size.height)
collectionViewLayout:[UICollectionViewFlowLayout new]];
[secondView setBackgroundColor:[UIColor greenColor]];
[secondView setTag:1];
[secondView setDelegate:self];
[secondView setDataSource:self];
[self.collectionView addSubview:secondView];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:#selector(swipedRight)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:#selector(swipedLeft)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.collectionView addGestureRecognizer:swipeRight];
[self.collectionView addGestureRecognizer:swipeLeft];
Example of swipeRight and swipeLeft methods:
-(void)swipedRight {
// Switch to left collection view
[self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
}
-(void)swipedLeft {
// Switch to right collection view
[self.collectionView setContentOffset:CGPointMake(cVFrame.size.width, 0)
animated:YES];
}
And then it's not a big problem to implement DataSource methods (in your case you want to have 9 items on each page):
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
if (collectionView.tag == 1) {
// Second collection view
return self.dataArray.count % 9;
} else {
// Original collection view
return 9; // Or whatever
}
In method -collectionView:cellForRowAtIndexPath you will need to get data from your model with offset, if it's second collection view.
Also don't forget to register class for reusable cell for your second collection view as well. You can also create only one gesture recognizer and recognize swipes to the left and to the right. It's up to you.
I think, now it should work, try it out :-)
You have an object that implements the UICollectionViewDataSource protocol.
Inside collectionView:cellForItemAtIndexPath: simply return the correct item that you want to return.
I don't understand where there would be a problem.
Edit: ok, I see the problem. Here is the solution: http://www.skeuo.com/uicollectionview-custom-layout-tutorial , specifically steps 17 to 25. It's not a huge amount of work, and can be reused very easily.
This is my solution, I did not test with animations but I think it will be work well with a little changes, hope it helpful
CELLS_PER_ROW = 4;
CELLS_PER_COLUMN = 5;
CELLS_PER_PAGE = CELLS_PER_ROW * CELLS_PER_COLUMN;
UICollectionViewFlowLayout* flowLayout = (UICollectionViewFlowLayout*)collectionView.collectionViewLayout;
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.itemSize = new CGSize (size.width / CELLS_PER_ROW - delta, size.height / CELLS_PER_COLUMN - delta);
flowLayout.minimumInteritemSpacing = ..;
flowLayout.minimumLineSpacing = ..;
..
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger index = indexPath.row;
NSInteger page = index / CELLS_PER_PAGE;
NSInteger indexInPage = index - page * CELLS_PER_PAGE;
NSInteger row = indexInPage % CELLS_PER_COLUMN;
NSInteger column = indexInPage / CELLS_PER_COLUMN;
NSInteger dataIndex = row * CELLS_PER_ROW + column + page * CELLS_PER_PAGE;
id cellData = _data[dataIndex];
...
}
Related
I have a custom cell which should be spaced from the edges of the display. For that I use this:
- (void)setFrame:(CGRect)frame {
frame.origin.x += kCellSidesInset;
frame.size.width -= 2 * kCellSidesInset;
[super setFrame:frame];
}
I do have a button that hides/shows the bottom view of a stacked view inside the cell. For which I use this code:
- (IBAction)showCardDetails:(id)sender {
UITableView *cellTableView = (UITableView*)[[[[sender superview] superview] superview] superview ];
[cellTableView beginUpdates];
self.details.hidden = !self.details.hidden;
[cellTableView endUpdates];
// [cellTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationBottom];
// [cellTableView reloadData];
}
However when the table is updated to reflect the change the right padding becomes allot bigger. Then when I scroll a bit it gets fixed.
As much as I could visually judge it is like 3 times. Maybe it adds two more kCellSidesInset on the right but I doubt it.
Why is this happening and how can it be fixed? Maybe it can be avoid by instead of giving inset to the cell giving it to the UITableView (I have some trouble figuring how to do this).
PS. All the code is inside the CustomCell.m. I am open for a suggestion to a better way of getting the UITableView inside the action. Should I use selector in the CustomTableViewController.m to implement the action there when the cell is added?
EDIT: From what I can see the re rendering of the cells goes trough three phases.
Phase one, a couple of these:
Phase two, it updates the view cells:
And here everything looks good for now. The view that I want to hide/show is hidden/shown and all is good but then some sort of cleanup breaks the layout:
I solved the problem by refactoring the setFrame method to use the superview's frame of the cell as a reference point for the cell frame
- (void)setFrame:(CGRect)frame {
frame.origin.x = self.superview.frame.origin.x + kCellSidesInset;
frame.size.width = self.superview.frame.size.width - 2 * kCellSidesInset;
[super setFrame:frame];
}
The questions itself does not say much, but what I am trying to say is: how can one move the cell's content (let say a UILabel), so the label can be seen on screen while the collection view is being scrolled, until the collectionView's cell runs out of available space.
But, a picture is worth a thousand words:
I have something like this, a UICollectionViewCell with horizontal scroll.
Normally, when I scroll this is what it will happen:
But, what I would like to achieve is the names in the firsts cells to scroll to the right while there is space available in the cell, without forgetting that when there's no more space available it will start to truncate the tail, like: Keaton Pickett -> Keaton Pick... -> Keaton... -> etc,
I've been thinking about nesting the cell's content inside a UIScrollView and then scroll it by code when the collectionView scrolls.
I also thought changing the CGRect property of the cell's contents (in this case, the UILabel) while the view is scrolling (playing with the width and minX properties.
However, detecting when the, in this case, UILabel is starting to be out of the screen (like Kea in the first cell of the second picture) is turning to be a struggle.
In my real case scenario I have the UICollectionView (horizontal scroll) nested in UITableView (vertical scroll).
I will thank and appreciate your help in this predicament.
Best regards!
I prefer you to use the code
Objective C
- (void)checkVisibilityOfCell:(MyCustomUITableViewCell *)cell inScrollView:(UIScrollView *)aScrollView {
CGRect cellRect = [aScrollView convertRect:cell.frame toView:aScrollView.superview];
if (CGRectContainsRect(aScrollView.frame, cellRect))
[cell notifyCompletelyVisible];
[cells objectAtIndex:i].hidden= YES; // MAKE THE CELL VISIBLE
else
[cell notifyNotCompletelyVisible];
[cells objectAtIndex:i].hidden= NO; // MAKE THE CELL UNVISIBLE
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
NSArray* cells = myTableView.visibleCells;
NSUInteger cellCount = [cells count];
if (cellCount == 0)
return;
// Loop through All cells
for (NSUInteger i = 1; i < cellCount - 1; i++)
[[cells objectAtIndex:i] notifyCompletelyVisible];
}
I'm trying to make something similar to what UltraVisual for iOS already does. I'd like to make my pull-to-refresh be in a cell in-between other cells.
I think the following GIF animation explains it better:
It looks like the first cell fades out when pulling up, while when you pull down and you're at the top of the table, it adds a new cell right below the first one and use it as the pull-to-refresh.
Has anyone done anything similar?
Wrote this one for UV. Its actually way simpler than you're describing. Also, for what its worth, this view was written as a UICollectionView, but the logic still applies to UITableView.
There is only one header cell. Durring the 'refresh' animation, I simply set the content inset of the UICollectionView to hold it open. Then when I've finished with the reload, I animate the content inset back to the default value.
As for the springy fixed header, there's a couple of ways you can handle it. Quick and dirty is to use a UICollectionViewFlowLayout, and modify the attributes in - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
Here's some pseudo code assuming your first cell is the sticky header:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *layoutAttributes = [super layoutAttributesForElementsInRect:rect];
if ([self contentOffsetIsBelowZero]) {
for (UICollectionViewLayoutAttributes *attributes in layoutAttributes) {
if (attributes.indexPath.item == 0) {
CGPoint bottomOrigin = CGPointMake(0, CGRectGetMaxY(attributes.frame));
CGPoint converted = [self.collectionView convertPoint:bottomOrigin toView:self.collectionView.superview];
height = MAX(height, CGRectGetHeight(attributes.frame));
CGFloat offset = CGRectGetHeight(attributes.frame) - height;
attributes.frame = CGRectOffset(CGRectSetHeight(attributes.frame, height), 0, offset);
break;
}
}
}
Another approach would be to write a custom UICollectionViewLayout and calculate the CGRect's manually.
And finally, the 'fade out' is really nothing more than setting the opacity of the objects inside the first cell as it moves off screen. You can calculate the position of the cell on screen during - (void)applyLayoutAttributes… and set the opacity based on that.
Finally, something to note: In order to do any 'scroll based' updates with UICollectionView, you'll need to make sure - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds returns YES. You can do a simple optimisation check like:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
BOOL shouldInvalidate = [super shouldInvalidateLayoutForBoundsChange:newBounds];
if ([self contentOffsetIsBelowZero]) {
shouldInvalidate = YES;
}
return shouldInvalidate;
}
Again this is mostly pseudo code, so re-write based on your own implementation. Hope this helps!
Almost every time I write an app for a client I have to implement some kind of 'hack' to get UITableViewCells to dynamically become the right height. Depending on the content of the cells this can vary in difficulty.
I usually end up running through code that formats the cell twice, once in heightForRowAtIndexPath: and then again in cellForRowAtIndexPath:. I then use an array or dictionary to store either the height or the formatted cell object.
I've probably written and rewritten this code 20 times over the past 2 years. Why did Apple implement it in this order? It would be much more straightforward to configure the cells and THEN set the height either in cellForRowAtIndexPath: or shortly thereafter in heightForRowAtIndexPath:.
Is there a good reason for the existing order? Is there a better way to handle it?
Best guess: UITableView needs to know the total height of all cells so that it can know the percentage of scroll for the scroll bar and other needs.
Actually, in iOS 7, it doesn't have to work that way. You can now set an estimated height for your rows and calculate each row's real height only when that row is actually needed. (And I assume that this is exactly because people made complaints identical to yours: "Why do I have to do this twice?")
Thus you can postpone the height calculation and then memoize it the first time that row appears (this is for a simple one-section table, but it is easy to adapt it if you have multiple sections):
- (void)viewDidLoad {
[super viewDidLoad];
// create empty "sparse array" of heights, for later
NSMutableArray* heights = [NSMutableArray new];
for (int i = 0; i < self.modeldata.count; i++)
[heights addObject: [NSNull null]];
self.heights = heights;
self.tableView.estimatedRowHeight = 40; // new iOS 7 feature
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int ix = indexPath.row;
if ([NSNull null] == self.heights[ix]) {
h = // calculate _real_ height here, on demand
self.heights[ix] = #(h);
}
return [self.heights[ix] floatValue];
}
You supplied an estimated height, so all the heights are not asked for beforehand. You are asked for a height only before that row actually appears in the interface, either because it is showing initially or because you or the user scrolled to reveal it.
NOTE Also, note that if you use dequeueReusableCellWithIdentifier:forIndexPath: the cell you get has the correct final height already. That is the whole point of this method (as opposed to the earlier mere dequeueReusableCellWithIdentifier:).
I have a UITableView that is set to not enable scrolling, and it exists in a UIScrollView. I'm doing it this way as the design specs call for something that looks like a table view, (actually there are two of them side by side), and it would be much easier to implement tableviews rather than adding a whole bunch of buttons, (grouped table views).
Question is, I need to know how big to make the container view for the scrollview, so it scrolls the whole height of the table views. Once loaded, is there any way to find the height of a tableview? There is no contentView property like a scroll view, frame seems to be static, etc...
Any thoughts?
Use
CGRect lastRowRect= [tableView rectForRowAtIndexPath:index_path_for_your_last_row];
CGFloat contentHeight = lastRowRect.origin.y + lastRowRect.size.height;
You can then use the contentHeight variable to set the contentSize for the scrollView.
A more general solution that works for me:
CGFloat tableViewHeight(UITableView *tableView) {
NSInteger lastSection = tableView.numberOfSections - 1;
while (lastSection >= 0 && [tableView numberOfRowsInSection:lastSection] <= 0)
lastSection--;
if (lastSection < 0)
return 0;
CGRect lastFooterRect = [tableView rectForFooterInSection:lastSection];
return lastFooterRect.origin.y + lastFooterRect.size.height;
}
In addition to Andrei's solution, it accounts for empty sections and section footers.
UITableView is a subclass of UIScrollView, so it has a contentSize property that you should be able to use no problem:
CGFloat tableViewContentHeight = tableView.contentSize.height;
scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, tableViewContentHeight);
However, as several other SO questions have pointed out, when you make an update to a table view (like inserting a row), its contentSize doesn't appear to be updated immediately like it is for most other animated resizing in UIKit. In this case, you may need to resort to something like Michael Manner's answer. (Although I think it makes better sense implemented as a category on UITableView)
You can run over the sections and use the rectForSection to calculate the total height (this included footer and header as well!). In swift I use the following extension on UITableView
extension UITableView {
/**
Calculates the total height of the tableView that is required if you ware to display all the sections, rows, footers, headers...
*/
func contentHeight() -> CGFloat {
var height = CGFloat(0)
for sectionIndex in 0..<numberOfSections {
height += rectForSection(sectionIndex).size.height
}
return height
}
}