How to make custom cell height effective? - ios

Lately I have faced a problem with effeciency caused by heightForRowAtIndexPath:. Each time you have to draw cell you nerd to create it and calculate it size - it's so long!
One would say, why not use estimatedHeightForRowAtIndexPath: but when you pass estimation here you just loose accurancy so when you scroll to top some cells aren't visible at all...
I want to widen my knowledge in this matter. How do guys from Twitter, Facebook or Instagram did it?

I suppose you mean a situation when the height of a cell is determined by the content of the cell.
In general, the height of a cell in that case is calculated during layout process. There is no other way to calculate that height without performing layout at least once.
For example, you have a cell with a description label. You have a requirement to display the whole description as multiline text without truncating it. So, you have to make the description label of variable height.
When tableview asks you about cell’s height you have to calculate the number of lines required for the description text. This is exactly the same work you perform during layout of cell contents.
In a common case the layout process is a number of lightweight calculations. The idea is to extract that calculations code out of the cell class and access them directly as needed.
In the example below:
CellLayoutParams contains the initial information that should be taken into account when calculating layout. Here goes the data that should be shown by the cell and the cell width.
#interface CellLayoutParams : NSObject {
#property (nonatomic, copy) NSString* title;
#property (nonatomic, copy) NSString* description;
#property (nonatomic, assign) CGFloat width;
- (BOOL)isEqualToLayoutParams:(CellLayoutParams*)params;
#end
CellStyle is an object that describes the style attributes of the cell. E.g. the font of the description label, various cell paddings, margins and insets.
#interface CellStyle : NSObject
#property(nonatomic, strong) UIFont* titleFont;
#property(nonatomic, strong) UIFont* descriptionFont;
- (struct CellLayoutInfo)layoutInfoForParams:(CellLayoutParams*)params;
#end
#implementation CellStyle
- (struct CellLayoutInfo)layoutInfoForParams:(CellLayoutParams*)params {
CellLayoutInfo layoutInfo;
const CGPoint contentOffset = CGPointMake(kLeftMargin, kTopMargin);
const CGFloat contentWidth = params.width - kAccessoryWidth - kLeftMargin;
NSString* descriptionValue = params.description;
CGSize descriptionSize = [descriptionValue sizeWithFont: [self descriptionFont]
constrainedToSize: CGSizeMake(contentWidth, CGFLOAT_MAX)];
layoutInfo.descriptionFrame.size = descriptionSize;
layoutInfo.descriptionFrame.origin = CGPointMake(contentOffset.x, layoutInfo.titleFrame.origin.y + layoutInfo.titleFrame.size.height + kVerticalInset);
layoutInfo.preferredHeight = layoutInfo.descriptionFrame.origin.y + descriptionSize.height + kBottomMargin;
return layoutInfo
}
#end
CellLayoutInfo is a structure with calculated layout information: calculated frames and preferred height value.
typedef struct CellLayoutInfo {
CGRect titleFrame;
CGRect descriptionFrame;
CGFloat preferredHeight;
} CellLayoutInfo;
You just need to perform layout calculations to get the preferred height:
- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath*)indexPath {
MyData* dataItem = [self.data objectAtIndex:indexPath.row];
CellLayoutParams* layoutParams = [CellLayoutParams new];
layoutParams.description = dataItem.description;
layoutParams.width = table.bounds.size.width;
CellStyle* cellStyle = [CellStyle new];
CellLayoutInfo layoutInfo = [cellStyle layoutInfoForParams:layoutParams];
return layoutInfo.preferredHeight;
}
In cell's layoutSubviews you access the same calculated layout values:
- (void) layoutSubviews {
[super layoutSubviews];
CellLayoutParams* layoutParams = [CellLayoutParams new];
layoutParams.description = self.descriptionLabel.text;
layoutParams.width = self.bounds.size.width;
CellStyle* cellStyle = [CellStyle new];
CellLayoutInfo layoutInfo = [cellStyle layoutInfoForParams:layoutParams];
self.titleLabel.frame = layoutInfo.titleFrame;
self.descriptionLabel.frame = layoutInfo.descriptionFrame;
}
Few things to note:
You don't need to create multiple style objects. The style object is immutable and is the same for all cells.
The code of layout is not duplicated. The table view delegate and the cell are using the same layouting code.
You may perform few additional optimizations:
Cache CellLayoutInfo objects in the controller and reuse them. This is useful when there is much scrolling through the table.
Keep a copy of CellLayoutInfo and corresponding CellLayoutParams in the cell and when the cell is being reused just check if params where changed and if a new CellLayoutInfo should be calculated. This is useful when the table view is being reloaded frequently.
The only drawback is that you have to define all the styling and layout in the code.

Related

ASCollectionNode full-width layout for CellNode

I want to make cells full-width in ASCollectionNode, but I'll get CellNodes sized by content.
I have implemented layoutSpecThatFits:.
See the image
My way to achieve that is adding extra node with full width inside ASStaticLayoutSpec.
In header:
#property (strong, nonatomic) ASDisplayNode *stretchNode;
In init
_stretchNode = [ASDisplayNode new];
[self addSubnode:_stretchNode];
layoutSpecThatFits:
- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize {
_stretchNode.sizeRange = ASRelativeSizeRangeMakeWithExactCGSize(CGSizeMake(constrainedSize.max.width, 0.5f));
NSArray *children = #[];
ASStackLayoutSpec *mainStackLayoutSpec = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:0 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsStart children:children];
ASStaticLayoutSpec *mainStaticLayoutSpec = [ASStaticLayoutSpec staticLayoutSpecWithChildren:#[mainInsetsLayoutSpec, _stretchNode]];
return mainStaticLayoutSpec;
}
Important part here is to wrap your layout and stretchNode in ASStaticLayoutSpec. You can replace StackLayout with anything you want.

Why i can't move image and set text in label at the same time

I want to move background to the left like my character is walking and show number of walking but it can't do that at the same time. this method leftfootButton can only set text in label
- (IBAction)leftfootButton:(id)sender {
_bgGround.center = CGPointMake(_bgGround.center.x -50, _bgGround.center.y);
i = i+1;
self.show.text = [NSString stringWithFormat:#"%d",i];
}
If i comment the code that sets the text out then it can move background
- (IBAction)rightfootButton:(id)sender {
_bgGround.center = CGPointMake(_bgGround.center.x - 50, _bgGround.center.y);
i = i+1;
//self.show.text = [NSString stringWithFormat:#"%d",i];
}
what should i do?
You should not change frames directly when you use auto layout because layoutSubviews method will return frames to their previous position. This method is called by system in many cases. You could override it to set the frame rectangles of your subviews directly. But I recommend you to change constraints of your background view. Even if you did not set constraints to your views, they was added automatically.
When you use Layout Constraint then you should never change the frame, you should try to change the constraint, e.g.
Create a IBOutlet for x contraint for the view like below, make sure it's correctly connected.
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *xContraint;
Then in your action
- (IBAction)leftfootButton:(id)sender {
self.xContraint.constant -= 50;
i = i + 1;
self.show.text = [NSString stringWithFormat:#"%d", i];
}

Centering and sizeToFit subview at run time and during orientation changes

The is the first of several problems I'm having setting up some UIViews and subviews. I have a UIView that is dynamically positioned on screen at run time. That UIView (master) contains another UIView (child) which wraps a UIImageView and a UILabel. Here are the requirements I have for this arrangement:
The child UIView must stay centered in the master UIView when the device rotates.
The text in the UILabel can be very long or very short and the child UIView with the image and text must still remain centered.
I would like to avoid subclassing UIView to handle this scenario and I would also like to avoid any frame/positioning code in willRotateToInterfaceOrientation. I'd like to handle all of this with some autoresizingMask settings in I.B. and maybe a little forced resizing code, if possible.
This is the arrangement of controls in Interface Builder(highlighted in red):
With Interface Builder, the autoresizingMask properties have been set like so, for the described controls
UIView (master): Flexible top margin, Flexible left margin, Flexible right margin, Flexible width
UIView (child): Flexible top margin, Flexible bottom margin, Flexible left margin, Flexible right margin, Flexible width, Flexible height. (All modes, except None)
UIImageView: Flexible right margin
UILabel: Flexible right margin
This is the view (red bar with image and text) after it's been added programmatically at run time while in portrait mode:
The master UIView's background is a light-red colored image. The child UIView's background is slightly darker than that, and the UILabel's background is even darker. I colored them so that I could see their bounds as the app responded to rotation.
It's clear to me that:
It is not centered but ...
After changing the text from it's default value in I.B from "There is no data in this map extent." to "TEST1, 123." the label contracts correctly.
This is the view after it's been added while in portrait and then rotated to landscape mode:
From here I can see that:
It is still not centered and perhaps at its original frame origin prior to rotation
The UIView (child) has expanded to fill more of the screen when it shouldn't.
The UIView (master) has properly expanded to fill the screen width.
This is the code that got me where I am now. I call the method showNoDataStatusView from viewDidLoad:
// Assuming
#define kStatusViewHeight 20
- (void)showNoDataStatusView {
if (!self.noDataStatusView.superview) {
self.noDataStatusView.frame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.noDataStatusView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgRedStatus.png"]];
// Position the label view in the center
self.noDataStatusLabelView.center = CGPointMake(self.noDataStatusView.frame.size.width/2,
self.noDataStatusView.frame.size.height/2);
// Test different text
self.noDataStatusLabel.text = #"Testing, 123.";
// Size to fit label
[self.noDataStatusLabel sizeToFit];
// Test the status label view resizing
[self.noDataStatusLabelView resizeToFitSubviews];
// Add view as subview
[self.view addSubview:self.noDataStatusView];
}
}
Please note the following:
resizeToFitSubviews is a category I placed on UIView once I found that UIView's won't automatically resize to fit their subviews even when you call sizeToFit. This question, and this question explained the issue. See the code for the category, below.
I have thought about creating a UIView subclass that handles all this logic for me, but it seems like overkill. It should be simple to arrange this in I.B. right?
I have tried setting every resizing mask setting in the book, as well as adjusting the order in which the resizing of the label and view occur as well as the point at which the master view is added as a subview. Nothing seems to be working as I get odd results every time.
UIView resizeToFitSubviews category implementation method:
-(void)resizeToFitSubviews
{
float width = 0;
float height = 0;
// Loop through subviews to determine max height/width
for (UIView *v in [self subviews]) {
float fw = v.frame.origin.x + v.frame.size.width;
float fh = v.frame.origin.y + v.frame.size.height;
width = MAX(fw, width);
height = MAX(fh, height);
}
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, width, height)];
}
What I want to know is why the UIView (child) is not properly centered after it's superview is added to the view hierarchy. It looks as though its got the proper width, but is somehow retaining the frame it had in I.B. when the label read "There is no data in this map extent."
I want to also know why it's not centered after device rotation and whether or not the approach I'm taking here is wise. Perhaps this is causing the other issues I'm having. Any UIView layout help here would be greatly appreciated.
Thanks!
If you are able to target iOS 6 you could use the new Auto Layout functionality to make this much much easier to manage - I've been reading a great tutorial by Ray Wenderlich that seems to be perfect to solve the problem you are seeing.
The problem here is that my UIView (master) does not layout it's subviews automatically when the device rotates and the "springs & struts" layout method used to position the image and interior UIView was inefficient. I solved the problem by doing two things.
I got rid of the internal UIView (child) instance, leaving only the UIView (master) and inside of that a UILabel and UIImageView.
I then created a UIView subclass called StatusView and in it I implement the layoutSubviews method. In its constructor I add a UIImageView and UILabel and position them dynamically. The UILabel is positioned first based on the size of the text and then the UIImageView is placed just to the left of it and vertically centered. That's it. In layoutSubviews I ensure that the positions of the elements are adjusted for the new frame.
Additionally, since I need to swap the background, message and possibly the image in some circumstances, it made sense to go with a custom class. There may be memory issues here/there but I'll iron them out when I run through this with the profiling tool.
Finally, I'm not totally certain if this code is rock solid but it does work. I don't know if I need the layout code in my init method, either. Layout subviews seems to be called shortly after the view is added as a subview.
Here's my class header:
#import <UIKit/UIKit.h>
typedef enum {
StatusViewRecordCountType = 0,
StatusViewReachedMaxRecordCountType = 1,
StatusViewZoomInType = 2,
StatusViewConnectionLostType = 3,
StatusViewConnectionFoundType = 4,
StatusViewNoDataFoundType = 5,
StatusViewGeographyIntersectionsType = 6,
StatusViewRetreivingRecordsType = 7
} StatusViewType;
#interface StatusView : UIView
#property (strong, nonatomic) NSString *statusMessage;
#property (nonatomic) StatusViewType statusViewType;
- (id)initWithFrame:(CGRect)frame message:(NSString*)message type:(StatusViewType)type;
#end
... and implementation:
#import "StatusView.h"
#define kConstrainSizeWidthOffset 10
#define kImageBufferWidth 15
#interface StatusView ()
#property (nonatomic, strong) UILabel *statusMessageLabel;
#property (nonatomic, strong) UIFont *statusMessageFont;
#property (nonatomic, strong) UIImage *statusImage;
#property (nonatomic, strong) UIImageView *statusImageView;
#end
#implementation StatusView
#synthesize statusMessageLabel = _statusMessageLabel;
#synthesize statusMessageFont = _statusMessageFont;
#synthesize statusImageView = _statusImageView;
#synthesize statusMessage = _statusMessage;
#synthesize statusViewType = _statusViewType;
#synthesize statusImage = _statusImage;
- (id)initWithFrame:(CGRect)frame message:(NSString *)message type:(StatusViewType)type {
self = [super initWithFrame:frame];
if (self) {
if (message != nil) {
_statusMessage = message;
_statusMessageFont = [UIFont fontWithName:#"Avenir-Roman" size:15.0];
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel = [[UILabel alloc] initWithFrame:labelFrame];
_statusMessageLabel.backgroundColor = [UIColor clearColor];
_statusMessageLabel.textColor = [UIColor whiteColor];
_statusMessageLabel.font = _statusMessageFont;
// Set shadow and color
_statusMessageLabel.shadowOffset = CGSizeMake(0, 1);
_statusMessageLabel.shadowColor = [UIColor blackColor];
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
// Flex both the width and height as well as left and right margins
_statusMessageLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
// Set label text
_statusMessageLabel.text = _statusMessage;
[self addSubview:_statusMessageLabel];
}
self.statusViewType = type;
if (_statusImage != nil) {
// Create image view
_statusImageView = [[UIImageView alloc] initWithImage:_statusImage];
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
[self addSubview:_statusImageView];
}
}
return self;
}
- (void)layoutSubviews {
CGSize constrainSize = CGSizeMake(self.frame.size.width - kImageBufferWidth - kConstrainSizeWidthOffset, self.frame.size.height);
// Find the size appropriate for this message
CGSize messageSize = [_statusMessage sizeWithFont:_statusMessageFont constrainedToSize:constrainSize];
// Create label and position at center of status view
CGRect labelFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
messageSize.width,
messageSize.height);
_statusMessageLabel.frame = labelFrame;
// Center the label
CGPoint centerPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
_statusMessageLabel.center = centerPoint;
// Gets rid of fuzziness
_statusMessageLabel.frame = CGRectIntegral(_statusMessageLabel.frame);
if (_statusImageView != nil) {
// Vertically center the image
CGPoint centerPoint = CGPointMake(_statusMessageLabel.frame.origin.x - kImageBufferWidth,
self.frame.size.height / 2);
_statusImageView.center = centerPoint;
}
}
#pragma mark - Custom setters
- (void)setStatusMessage:(NSString *)message {
if (_statusMessage == message) return;
_statusMessage = message;
_statusMessageLabel.text = _statusMessage;
// Force layout of subviews
[self setNeedsLayout];
[self layoutIfNeeded];
}
- (void)setStatusViewType:(StatusViewType)statusViewType {
_statusViewType = statusViewType;
UIColor *bgColor = nil;
switch (_statusViewType) {
// Changes background and image based on type
}
self.backgroundColor = bgColor;
if (_statusImageView != nil) {
_statusImageView.image = _statusImage;
}
}
#end
Then in my view controller I can do this:
CGRect statusFrame = CGRectMake(self.mapView.frame.origin.x,
self.mapView.frame.origin.y,
self.mapView.frame.size.width,
kStatusViewHeight);
self.staticStatusView = [[StatusView alloc] initWithFrame:statusFrame message:#"600 records found :)" type:StatusViewRecordCountType];
self.staticStatusView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:self.staticStatusView];
... and later on I can change it up by doing this:
self.staticStatusView.statusMessage = #"No data was found here";
self.staticStatusView.statusViewType = StatusViewNoDataFoundType;
Now I've got a reusable class rather than 12 UIView instances floating around my NIB with various settings and properties.

UICollectionView flowLayout not wrapping cells correctly

I have a UICollectionView with a FLowLayout. It will work as I expect most of the time, but every now and then one of the cells does not wrap properly. For example, the the cell that should be on in the first "column" of the third row if actually trailing in the second row and there is just an empty space where it should be (see diagram below). All you can see of this rouge cell is the left hand side (the rest is cut off) and the place it should be is empty.
This does not happen consistently; it is not always the same row. Once it has happened, I can scroll up and then back and the cell will have fixed itself. Or, when I press the cell (which takes me to the next view via a push) and then pop back, I will see the cell in the incorrect position and then it will jump to the correct position.
The scroll speed seems to make it easier to reproduce the problem. When I scroll slowly, I can still see the cell in the wrong position every now and then, but then it will jump to the correct position straight away.
The problem started when I added the sections insets. Previously, I had the cells almost flush against the collection bounds (little, or no insets) and I did not notice the problem. But this meant the right and left of the collection view was empty. Ie, could not scroll. Also, the scroll bar was not flush to the right.
I can make the problem happen on both Simulator and on an iPad 3.
I guess the problem is happening because of the left and right section insets... But if the value is wrong, then I would expect the behavior to be consistent. I wonder if this might be a bug with Apple? Or perhaps this is due to a build up of the insets or something similar.
Follow up: I have been using this answer below by Nick for over 2 years now without a problem (in case people are wondering if there are any holes in that answer - I have not found any yet). Well done Nick.
There is a bug in UICollectionViewFlowLayout's implementation of layoutAttributesForElementsInRect that causes it to return TWO attribute objects for a single cell in certain cases involving section insets. One of the returned attribute objects is invalid (outside the bounds of the collection view) and the other is valid. Below is a subclass of UICollectionViewFlowLayout that fixes the problem by excluding cells outside of the collection view's bounds.
// NDCollectionViewFlowLayout.h
#interface NDCollectionViewFlowLayout : UICollectionViewFlowLayout
#end
// NDCollectionViewFlowLayout.m
#import "NDCollectionViewFlowLayout.h"
#implementation NDCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *newAttributes = [NSMutableArray arrayWithCapacity:attributes.count];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
if ((attribute.frame.origin.x + attribute.frame.size.width <= self.collectionViewContentSize.width) &&
(attribute.frame.origin.y + attribute.frame.size.height <= self.collectionViewContentSize.height)) {
[newAttributes addObject:attribute];
}
}
return newAttributes;
}
#end
See this.
Other answers suggest returning YES from shouldInvalidateLayoutForBoundsChange, but this causes unnecessary recomputations and doesn't even completely solve the problem.
My solution completely solves the bug and shouldn't cause any problems when Apple fixes the root cause.
Put this into the viewController that owns the collection view
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
[self.collectionView.collectionViewLayout invalidateLayout];
}
i discovered similar problems in my iPhone application. Searching the Apple dev forum brought me this suitable solution which worked in my case and will probably in your case too:
Subclass UICollectionViewFlowLayout and override shouldInvalidateLayoutForBoundsChange to return YES.
//.h
#interface MainLayout : UICollectionViewFlowLayout
#end
and
//.m
#import "MainLayout.h"
#implementation MainLayout
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
#end
A Swift version of Nick Snyder's answer:
class NDCollectionViewFlowLayout : UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
let contentSize = collectionViewContentSize
return attributes?.filter { $0.frame.maxX <= contentSize.width && $0.frame.maxY < contentSize.height }
}
}
I've had this problem as well for a basic gridview layout with insets for margins. The limited debugging I've done for now is implementing - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect in my UICollectionViewFlowLayout subclass and by logging what the super class implementation returns, which clearly shows the problem.
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attrsList = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *attrs in attrsList) {
NSLog(#"%f %f", attrs.frame.origin.x, attrs.frame.origin.y);
}
return attrsList;
}
By implementing - (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath I can also see that it seems to return the wrong values for itemIndexPath.item == 30, which is factor 10 of my gridview's number of cells per line, not sure if that's relevant.
- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath {
UICollectionViewLayoutAttributes *attrs = [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];
NSLog(#"initialAttrs: %f %f atIndexPath: %d", attrs.frame.origin.x, attrs.frame.origin.y, itemIndexPath.item);
return attrs;
}
With a lack of time for more debugging, the workaround I've done for now is reduced my collectionviews width with an amount equal to the left and right margin. I have a header that still needs the full width so I've set clipsToBounds = NO on my collectionview and then also removed the left and right insets on it, seems to work. For the header view to then stay in place you need to implement frame shifting and sizing in the layout methods that are tasked with returning layoutAttributes for the header view.
I have added a bug report to Apple. What works for me is to set bottom sectionInset to a value less than top inset.
I was experiencing the same cell-deplacing-problem on the iPhone using a UICollectionViewFlowLayout and so I was glad finding your post. I know you are having the problem on an iPad, but I am posting this because I think it is a general issue with the UICollectionView. So here is what I found out.
I can confirm that the sectionInset is relevant to that problem. Besides that the headerReferenceSize also has influence whether a cell is deplaced or not. (This makes sense since it is needed for calcuating the origin.)
Unfortunately, even different screen sizes have to be taken into account. When playing around with the values for these two properties, I experienced that a certain configuration worked either on both (3.5" and 4"), on none, or on only one of the screen sizes. Usually none of them. (This also makes sense, since the bounds of the UICollectionView changes, therefore I did not experience any disparity between retina and non-retina.)
I ended up setting the sectionInset and headerReferenceSize depending on the screen size. I tried about 50 combinations until I found values under which the problem did not occure anymore and the layout was visually acceptable. It is very difficult to find values which work on both screen sizes.
So summarizing, I just can recommend you to play around with the values, check these on different screen sizes and hope that Apple will fix this issue.
I've just encountered a similar issue with cells disappearing after UICollectionView scroll on iOS 10 (got no problems on iOS 6-9).
Subclassing of UICollectionViewFlowLayout and overriding method layoutAttributesForElementsInRect: doesn't work in my case.
The solution was simple enough. Currently I use an instance of UICollectionViewFlowLayout and set both itemSize and estimatedItemSize (I didn't use estimatedItemSize before) and set it to some non-zero size.
Actual size is calculating in collectionView:layout:sizeForItemAtIndexPath: method.
Also, I've removed a call of invalidateLayout method from layoutSubviews in order to avoid unnecessary reloads.
I just experienced a similar issue but found a very different solution.
I am using a custom implementation of UICollectionViewFlowLayout with a horizontal scroll. I am also creating custom frame locations for each cell.
The problem that I was having was that [super layoutAttributesForElementsInRect:rect] wasn't actually returning all of the UICollectionViewLayoutAttributes that should be displayed on screen. On calls to [self.collectionView reloadData] some of the cells would suddenly be set to hidden.
What I ended up doing was to create a NSMutableDictionary that cached all of the UICollectionViewLayoutAttributes that I have seen so far and then include any items that I know should be displayed.
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray * originAttrs = [super layoutAttributesForElementsInRect:rect];
NSMutableArray * attrs = [NSMutableArray array];
CGSize calculatedSize = [self calculatedItemSize];
[originAttrs enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * attr, NSUInteger idx, BOOL *stop) {
NSIndexPath * idxPath = attr.indexPath;
CGRect itemFrame = [self frameForItemAtIndexPath:idxPath];
if (CGRectIntersectsRect(itemFrame, rect))
{
attr = [self layoutAttributesForItemAtIndexPath:idxPath];
[self.savedAttributesDict addAttribute:attr];
}
}];
// We have to do this because there is a bug in the collection view where it won't correctly return all of the on screen cells.
[self.savedAttributesDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray * cachedAttributes, BOOL *stop) {
CGFloat columnX = [key floatValue];
CGFloat leftExtreme = columnX; // This is the left edge of the element (I'm using horizontal scrolling)
CGFloat rightExtreme = columnX + calculatedSize.width; // This is the right edge of the element (I'm using horizontal scrolling)
if (leftExtreme <= (rect.origin.x + rect.size.width) || rightExtreme >= rect.origin.x) {
for (UICollectionViewLayoutAttributes * attr in cachedAttributes) {
[attrs addObject:attr];
}
}
}];
return attrs;
}
Here is the category for NSMutableDictionary that the UICollectionViewLayoutAttributes are being saved correctly.
#import "NSMutableDictionary+CDBCollectionViewAttributesCache.h"
#implementation NSMutableDictionary (CDBCollectionViewAttributesCache)
- (void)addAttribute:(UICollectionViewLayoutAttributes*)attribute {
NSString *key = [self keyForAttribute:attribute];
if (key) {
if (![self objectForKey:key]) {
NSMutableArray *array = [NSMutableArray new];
[array addObject:attribute];
[self setObject:array forKey:key];
} else {
__block BOOL alreadyExists = NO;
NSMutableArray *array = [self objectForKey:key];
[array enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *existingAttr, NSUInteger idx, BOOL *stop) {
if ([existingAttr.indexPath compare:attribute.indexPath] == NSOrderedSame) {
alreadyExists = YES;
*stop = YES;
}
}];
if (!alreadyExists) {
[array addObject:attribute];
}
}
} else {
DDLogError(#"%#", [CDKError errorWithMessage:[NSString stringWithFormat:#"Invalid UICollectionVeiwLayoutAttributes passed to category extension"] code:CDKErrorInvalidParams]);
}
}
- (NSArray*)attributesForColumn:(NSUInteger)column {
return [self objectForKey:[NSString stringWithFormat:#"%ld", column]];
}
- (void)removeAttributesForColumn:(NSUInteger)column {
[self removeObjectForKey:[NSString stringWithFormat:#"%ld", column]];
}
- (NSString*)keyForAttribute:(UICollectionViewLayoutAttributes*)attribute {
if (attribute) {
NSInteger column = (NSInteger)attribute.frame.origin.x;
return [NSString stringWithFormat:#"%ld", column];
}
return nil;
}
#end
The above answers don't work for me, but after downloading the images, I replaced
[self.yourCollectionView reloadData]
with
[self.yourCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
to refresh and it can show all cells correctly, you can try it.
This might be a little late but make sure you are setting your attributes in prepare() if possible.
My issue was that the cells were laying out, then getting update in layoutAttributesForElements. This resulted in a flicker effect when new cells came into view.
By moving all the attribute logic into prepare, then setting them in UICollectionViewCell.apply() it eliminated the flicker and created butter smooth cell displaying 😊
Swift 5 version of Nick Snyder answer:
class NDCollectionViewFlowLayout: UICollectionViewFlowLayout {
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
var newAttributes = [AnyHashable](repeating: 0, count: attributes?.count ?? 0)
for attribute in attributes ?? [] {
if (attribute.frame.origin.x + attribute.frame.size.width <= collectionViewContentSize.width) && (attribute.frame.origin.y + attribute.frame.size.height <= collectionViewContentSize.height) {
newAttributes.append(attribute)
}
}
return newAttributes as? [UICollectionViewLayoutAttributes]
}
}
Or you could use extension of UICollectionViewFlowLayout:
extension UICollectionViewFlowLayout {
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
var newAttributes = [AnyHashable](repeating: 0, count: attributes?.count ?? 0)
for attribute in attributes ?? [] {
if (attribute.frame.origin.x + attribute.frame.size.width <= collectionViewContentSize.width) && (attribute.frame.origin.y + attribute.frame.size.height <= collectionViewContentSize.height) {
newAttributes.append(attribute)
}
}
return newAttributes as? [UICollectionViewLayoutAttributes]
}
}

iOS UITableView AutoSizing Cell with Section Index

I have an app where I load a large plist file in a tableview. This plist file is as a book. It contains chapters and lines. Each row has different length depending on the line length and therefore I need to resize the cell automatically.
I am using storyboard and standard tableview and cell. Cell style=basic and the cell label is set to text=plain lines=0 linebreaks=wordwrap
Up to there, no problem resizing the cell height to the proper size. As the cell height is defined before the text is inserted in the label we have to do it by the well known method of using CGsize and I do it like that (it's working fine)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:
(NSIndexPath*)indexPath
{
NSUInteger section = [indexPath section];
NSString *key = [chapters objectAtIndex:section];
NSArray *linesSection = [lines objectForKey:key];
NSString* theText = [linesSection objectAtIndex:indexPath.row];
int labelWidth = LW_CHAPTERINDEX_10;
if (chapters.count < 100){
if (chapters.count < NB_MIN_CHAP){
labelWidth = LABELWIDTH;
} else {
labelWidth = LW_CHAPTERINDEX_10;
}
}
CGSize textSize = [theText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(labelWidth, MAXFLOAT)
lineBreakMode:UILineBreakModeWordWrap];
return textSize.height;
}
The problem is the hardcoding depending on the index. For now I have 3 possibilites.
No index
Index with numbers below 10
Index with numbers below 100
and in the code this part
int labelWidth = LW_CHAPTERINDEX_10;
if (chapters.count < 100){
if (chapters.count < NB_MIN_CHAP){
labelWidth = LABELWIDTH;
} else {
labelWidth = LW_CHAPTERINDEX_10;
}
}
is the hardcoding depending on the 3 possibilities.
I find this was of doing weird, especially if apple will start to deliver more different screen sizes.
QUESTION
How can I get the index width at runtime to determine my label width ?
For example i would like to program something like screen.width - index-width to get the label width.
Or any other that should allow it to be dynamical and no more statically hardcoded.
Unfortunately there is no (standard) way you can directly access the section index subview. However, you can use the methods for calculating the CGSize of text to determine dynamically the width of the section index.
You could determine all possible strings to be returned by sectionIndexTitlesForTableView: beforehand and calculate the necessary size, perhaps padding with some extra pixels left and right. Maybe it is necessary to make some experiments to determine the correct font and size.
Now your approach with something like screenSize.width - textSize.width - 2*PADDING should be viable. The only hardcoded thing is now the padding, which should not break things when new screen sizes are introduced.
Ok, to save other people a few hours of work....I laboriously tested various fonts and sizes and margins, comparing them to a UIView hierarchy dump of an actual table view with an index, to arrive at this method which will return the width of a table index, so that the bounds of the table view cell content can be calculated as table_width - index_width. I will point out that there is often another 20 pixel right-side amount reserved for an accessory view.
I also discovered that the cell.contentView.bounds is NOT correctly set until AFTER cellForRowAtIndexPath and willDisplayCell methods are called, so trying to grab the value during those calls is doomed to fail. It is set correctly by the time viewDidAppear is called.
I have no idea how to calculate the index width if the device language is set for a non-English alphabet.
- (CGFloat) getMaxIndexViewWidth
{
CGFloat indexMargin = 21.0;
NSArray *sectionTitles = [self sectionIndexTitlesForTableView:nil]; //NOTE -- if multiple tables, pass real one in
CGFloat maxWidth11 = CGFLOAT_MIN;
for(NSString *title in sectionTitles)
{
CGFloat titleWidth11 = [title sizeWithFont:[UIFont fontWithName:#"Helvetica-Bold" size:11.0f]].width;
maxWidth11 = MAX(maxWidth11, titleWidth11);
}
return maxWidth11+indexMargin;
}

Resources