SlideShare a Scribd company logo
Collection view custom
layout
Waterfall layout case study
iOS Practice Leaders
Anatoly Tukhtarov
Introduction
UICollectionView is available since iOS 6
Allows present collections of data with custom
layout
Still in development
Agenda
• UICollectionView and its views
• UICollectionViewLayout and its friends
• Waterfall collection view layout
UICollectionView views
Managed by collection view’s data source (i.e. represent
some data)
• Cells — UICollectionViewCell
• Supplementary views (section’s or collection view’s headers, footers, etc.) —
UICollectionReusableView
Managed by collection view’s layout
• Decoration views (items separators, shadows, borders, etc.) —
UICollectionReusableView
Only cells are selectable
How does collection view
know how to place its
views?
UICollectionViewLayout
UICollectionViewLayout
A kind of data source to provide visual information,
not data
Responsible for locations and sizes of all the cells,
supplementary and decoration views
Does not apply data to views
UICollectionViewLayout
Classes
UICollectionViewLayoutAttributes
• view’s layout attributes like frame, alpha,
transform, etc.
• created and configured by layout
• must adopt NSCopying protocol
• must override equality methods
(-hash, -isEqual:)
• applied by collection view
UICollectionViewLayout
Classes
UICollectionViewLayoutInvalidationContext
• available since iOS 7
• declares which parts of layout need to be updated
on layout invalidation
• capital update for iOS 8
Waterfall layout
Documents list application
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Source code: https://github.com/swordfishyou/documents-app
Designing layout
• Number of columns in section
• Column width
• Cell size
• Cell frame
• Intercolumn and interline
spacings, etc.
• Cache all the possible values
layout delegate
data source
layout
Building layout
- (void)buildLayout {
if (self.isPreparingLayout) {
return;
}
self.preparingLayout = YES;
/// Calculate items sizes and columns metrics
if (!self.isLayoutDataValid) {
[self buildLayoutFromDataSource];
self.layoutDataValid = YES;
}
self.layoutSize = CGSizeZero;
[self.layoutAttributes removeAllObjects];
/// Calculate (reuse) layout attributes
[self calculateLayoutAttributes];
self.preparingLayout = NO;
}
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Cell size (self-sizing cells)
- (CGSize)collectionView:(UICollectionView *)collectionView
sizeFittingSize:(CGSize)fittingSize
forItemAtIndexPath:(NSIndexPath *)indexPath {
FLSCollectionViewCell *cell = [self collectionView:collectionView
cellForItemAtIndexPath:indexPath];
CGRect frame = cell.frame;
frame.size = fittingSize;
cell.frame = frame;
CGSize size;
[cell layoutIfNeeded];
size = [cell.contentView
systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
[cell removeFromSuperview];
return size;
}
Auto layouts case
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Layout metrics
• Items’ sizes and attributes by index path
• Column metrics by section
• index
• section
• size
• items’ indexes in column
Cell frame
- (CGRect)itemFrameAtIndexPath:(NSIndexPath *)indexPath {
CGRect frame;
frame.size = ...; /// use cached value
CGFloat topOffset = 0.0;
for (NSInteger section = 0; section < indexPath.section; ++section) {
/// Shift vertically by sections above
}
NSInteger numberOfColumnsInSection = ...;
NSInteger itemColumn = indexPath.item % numberOfColumnsInSection;
FLSColumnLayoutMetrics *columnMetrics = ...;
for (NSInteger item = 0; item < indexPath.item; ++item) {
if ([columnMetrics.itemIndexes containsIndex:item]) {
/// Shift vertically by items in column
}
}
frame.origin.y = topOffset;
CGFloat leftOffset = itemColumn * self.minimumItercolumnSpacing;
for (NSInteger column = 0; column < itemColumn; ++column) {
/// Shift horizontally by columns left
}
/// Centre cell in item’s column
return frame;
}
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Layout invalidation
@interface FLSCollectionViewLayoutInvalidationContext :
UICollectionViewLayoutInvalidationContext
@property (nonatomic, assign) BOOL invalidateLayoutMetrics;
@end
+ (Class)invalidationContextClass;
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;
- (UICollectionViewLayoutInvalidationContext *)
invalidationContextForBoundsChange:(CGRect)newBounds;
- (void)invalidateLayoutWithContext:
(FLSCollectionViewLayoutInvalidationContext *)context;
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Drag and drop
• Consider to use gestures controller or state
machine
• Layout is responsible for changing frame of a
dragging item
• Data source is responsible for handling motion
actions (like reorder array, etc.)
General ideas
Drag and drop
- (void)beginDraggingItemAtIndexPath:(NSIndexPath *)indexPath {
/// Snapshot cell and index path
self.draggingIndexPath = indexPath;
UICollectionViewCell *cell = ...;
UIView *snapshot = [cell snapshotViewAfterScreenUpdates:NO];
self.draggingView = snapshot;
[self.collectionView addSubview:self.draggingView];
/// Calculate drag bounds if needed
[UIView animateWithDuration:animationDuration
animations:^{
/// Indicate dragging item with animation
} completion:^(BOOL finished) {
/// Invalidate layout
}];
}
Begin dragging
Drag and drop
- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture {
switch (gesture.state) {
case UIGestureRecognizerStateChanged:{
[self scheduleDraggingHoldTimer];
/// Calculate new centre of the dragging view
CGPoint translation = [gesture translationInView:self.collectionView];
CGPoint diff = ...;
self.lastTranslation = translation;
CGPoint center = ...;
[self constrainPointToDragBounds:&center];
self.draggingView.center = center;
/// Trigger autoscroll
break;
}
case UIGestureRecognizerStateEnded:
/// Invalidate timers
break;
}
}
Handle pan gesture
Drag and drop
- (void)handleDraggindHold:(NSTimer *)timer {
FLSDataSource *dataSource = self.collectionView.dataSource;
NSIndexPath *newIndexPath = [self.collectionView
indexPathForItemAtPoint:self.draggingView.center];
if (newIndexPath != nil &&
![newIndexPath isEqual:self.draggingIndexPath]) {
BOOL canMove = ...; /// Use data source
if (canMove) {
self.draggingIndexPath = newIndexPath;
[dataSource collectionView:self.collectionView
moveItemAtIndexPath:self.lastSourceIndexPath
toIndexPath:newIndexPath isHeld:YES];
self.lastSourceIndexPath = newIndexPath;
/// Invalidate layout
}
}
}
Handle hold
Documents application
• Landscape and portrait items A4 scale
• Multiple waterfall columns for iPad and iPhone
• Number of columns must be changed on device
rotation
• Drag and drop items like on home screen
• Autoscroll while dragging
v 0.1
Autoscroll
• Consider to use CADisplayLink instead of
NSTimer
• Invalidate dragging hold timer while autoscrolling
• Calculate autoscroll direction and velocity while
dragging
• Calculate dragging view’s frame and collection
view’s contentOffset
Autoscroll
CGRect autoscrollFrame = UIEdgeInsetsInsetRect(self.collectionView.bounds,
self.autoscrollTriggerInsets);
CGPoint location = [gesture locationInView:self.collectionView];
CGFloat top = CGRectGetMinY(autoscrollFrame);
CGFloat bottom = CGRectGetMaxY(autoscrollFrame);
if (location.y < top) {
self.autosctollVelocity = 10 * (top - location.y);
[self scheduleAutoscrollTimerWithDirection:FLSAutoscrollDirectionUp];
} else if (location.y > bottom) {
self.autosctollVelocity = 10 * (location.y - bottom);
[self scheduleAutoscrollTimerWithDirection:FLSAutoscrollDirectionDown];
} else {
[self invalidateAutoscrollTimer];
}
Trigger autoscroll
Autoscroll
CGFloat distance = rintf(self.autosctollVelocity / 60.0);
switch (self.autoscrollDirection) {
/// Visually stop autoscroll if bottom of the content was
reached
case FLSAutoscrollDirectionDown: {
break;
}
/// Visually stop autoscroll if top of the content was reached
default:
break;
}
CGPoint translation = CGPointMake(0, distance);
CGPoint newCenter = ...;
[self constrainPointToDragBounds:&newCenter];
self.draggingView.center = newCenter;
self.collectionView.contentOffset = ...;
Handle autoscroll
Recap
• Cache all the possible values: calculate once and
reuse
• Auto layout is your friend
• Invalidate layout rationally
• Measure, measure and… measure
More information
WWDC 2014 — Session 232
Advanced User Interfaces with Collection View
Source code: https://developer.apple.com/wwdc/resources/sample-code/
WWDC 2014 — Session 226
What's New in Table and Collection Views
Collection View Programming Guide for iOS
Creating Custom Layout
Yalantis
Excel Page Layout for Collection View
http://yalantis.com/blog/data-grid-with-freeze-columns-play-by-your-rules/
WWDC 2012 — Session 219
Advanced Collection Views and Building Custom Layout
7th iOS Practice Leaders
Introduction to Auto Layout
Presentation

More Related Content

Similar to Collection view layout

Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
Ketan Raval
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core DataAllan Davis
 
iOS
iOSiOS
Session 14 - Working with table view and search bar
Session 14 - Working with table view and search barSession 14 - Working with table view and search bar
Session 14 - Working with table view and search barVu Tran Lam
 
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Vu Tran Lam
 
Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Michael Shrove
 
Declarative UI on iOS without SwiftUI (中文)
Declarative UI on iOS without SwiftUI (中文)Declarative UI on iOS without SwiftUI (中文)
Declarative UI on iOS without SwiftUI (中文)
Shih-Ting Huang
 
CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012
Jesse Collis
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
Jesse Collis
 
Hello Android
Hello AndroidHello Android
Hello Android
Trong Dinh
 
IOS APPs Revision
IOS APPs RevisionIOS APPs Revision
IOS APPs Revision
Muhammad Amin
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
Andrea Prearo
 
iOS performance: tips and tricks to do it better
iOS performance: tips and tricks to do it betteriOS performance: tips and tricks to do it better
iOS performance: tips and tricks to do it better
Julian Król
 
Android Screen Containers & Layouts
Android Screen Containers & LayoutsAndroid Screen Containers & Layouts
Android Screen Containers & Layouts
Vijay Rastogi
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChart
David Keener
 
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
Saulo Arruda
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's NewNascentDigital
 
Mobile Application Development class 006
Mobile Application Development class 006Mobile Application Development class 006
Mobile Application Development class 006
Dr. Mazin Mohamed alkathiri
 

Similar to Collection view layout (20)

Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core Data
 
iOS
iOSiOS
iOS
 
Session 14 - Working with table view and search bar
Session 14 - Working with table view and search barSession 14 - Working with table view and search bar
Session 14 - Working with table view and search bar
 
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
 
Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)
 
Declarative UI on iOS without SwiftUI (中文)
Declarative UI on iOS without SwiftUI (中文)Declarative UI on iOS without SwiftUI (中文)
Declarative UI on iOS without SwiftUI (中文)
 
CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012CATiled Layer - Melbourne Cocoheads February 2012
CATiled Layer - Melbourne Cocoheads February 2012
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
 
Hello Android
Hello AndroidHello Android
Hello Android
 
201104 iphone navigation-based apps
201104 iphone navigation-based apps201104 iphone navigation-based apps
201104 iphone navigation-based apps
 
IOS APPs Revision
IOS APPs RevisionIOS APPs Revision
IOS APPs Revision
 
Optimize CollectionView Scrolling
Optimize CollectionView ScrollingOptimize CollectionView Scrolling
Optimize CollectionView Scrolling
 
iOS performance: tips and tricks to do it better
iOS performance: tips and tricks to do it betteriOS performance: tips and tricks to do it better
iOS performance: tips and tricks to do it better
 
Android Screen Containers & Layouts
Android Screen Containers & LayoutsAndroid Screen Containers & Layouts
Android Screen Containers & Layouts
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChart
 
Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4Desenvolvimento iOS - Aula 4
Desenvolvimento iOS - Aula 4
 
iOS Development: What's New
iOS Development: What's NewiOS Development: What's New
iOS Development: What's New
 
Mobile Application Development class 006
Mobile Application Development class 006Mobile Application Development class 006
Mobile Application Development class 006
 
Couchbase Talk
Couchbase TalkCouchbase Talk
Couchbase Talk
 

More from Ciklum Ukraine

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev
Ciklum Ukraine
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko
Ciklum Ukraine
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_Design
Ciklum Ukraine
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developers
Ciklum Ukraine
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch Application
Ciklum Ukraine
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Ciklum Ukraine
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015
Ciklum Ukraine
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++
Ciklum Ukraine
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layout
Ciklum Ukraine
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
Ciklum Ukraine
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
Ciklum Ukraine
 
Material design
Material designMaterial design
Material design
Ciklum Ukraine
 
Kanban development
Kanban developmentKanban development
Kanban development
Ciklum Ukraine
 
Mobile sketching
Mobile sketching Mobile sketching
Mobile sketching
Ciklum Ukraine
 
More UX in our life
More UX in our lifeMore UX in our life
More UX in our life
Ciklum Ukraine
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
Ciklum Ukraine
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
Ciklum Ukraine
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Ciklum Ukraine
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Ciklum Ukraine
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
Ciklum Ukraine
 

More from Ciklum Ukraine (20)

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_Design
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developers
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch Application
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layout
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Material design
Material designMaterial design
Material design
 
Kanban development
Kanban developmentKanban development
Kanban development
 
Mobile sketching
Mobile sketching Mobile sketching
Mobile sketching
 
More UX in our life
More UX in our lifeMore UX in our life
More UX in our life
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
 

Recently uploaded

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 

Recently uploaded (20)

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 

Collection view layout

  • 1. Collection view custom layout Waterfall layout case study iOS Practice Leaders Anatoly Tukhtarov
  • 2. Introduction UICollectionView is available since iOS 6 Allows present collections of data with custom layout Still in development
  • 3. Agenda • UICollectionView and its views • UICollectionViewLayout and its friends • Waterfall collection view layout
  • 4. UICollectionView views Managed by collection view’s data source (i.e. represent some data) • Cells — UICollectionViewCell • Supplementary views (section’s or collection view’s headers, footers, etc.) — UICollectionReusableView Managed by collection view’s layout • Decoration views (items separators, shadows, borders, etc.) — UICollectionReusableView Only cells are selectable
  • 5. How does collection view know how to place its views? UICollectionViewLayout
  • 6. UICollectionViewLayout A kind of data source to provide visual information, not data Responsible for locations and sizes of all the cells, supplementary and decoration views Does not apply data to views
  • 7. UICollectionViewLayout Classes UICollectionViewLayoutAttributes • view’s layout attributes like frame, alpha, transform, etc. • created and configured by layout • must adopt NSCopying protocol • must override equality methods (-hash, -isEqual:) • applied by collection view
  • 8. UICollectionViewLayout Classes UICollectionViewLayoutInvalidationContext • available since iOS 7 • declares which parts of layout need to be updated on layout invalidation • capital update for iOS 8
  • 10. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1 Source code: https://github.com/swordfishyou/documents-app
  • 11. Designing layout • Number of columns in section • Column width • Cell size • Cell frame • Intercolumn and interline spacings, etc. • Cache all the possible values layout delegate data source layout
  • 12. Building layout - (void)buildLayout { if (self.isPreparingLayout) { return; } self.preparingLayout = YES; /// Calculate items sizes and columns metrics if (!self.isLayoutDataValid) { [self buildLayoutFromDataSource]; self.layoutDataValid = YES; } self.layoutSize = CGSizeZero; [self.layoutAttributes removeAllObjects]; /// Calculate (reuse) layout attributes [self calculateLayoutAttributes]; self.preparingLayout = NO; }
  • 13. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1
  • 14. Cell size (self-sizing cells) - (CGSize)collectionView:(UICollectionView *)collectionView sizeFittingSize:(CGSize)fittingSize forItemAtIndexPath:(NSIndexPath *)indexPath { FLSCollectionViewCell *cell = [self collectionView:collectionView cellForItemAtIndexPath:indexPath]; CGRect frame = cell.frame; frame.size = fittingSize; cell.frame = frame; CGSize size; [cell layoutIfNeeded]; size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; [cell removeFromSuperview]; return size; } Auto layouts case
  • 15. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1
  • 16. Layout metrics • Items’ sizes and attributes by index path • Column metrics by section • index • section • size • items’ indexes in column
  • 17. Cell frame - (CGRect)itemFrameAtIndexPath:(NSIndexPath *)indexPath { CGRect frame; frame.size = ...; /// use cached value CGFloat topOffset = 0.0; for (NSInteger section = 0; section < indexPath.section; ++section) { /// Shift vertically by sections above } NSInteger numberOfColumnsInSection = ...; NSInteger itemColumn = indexPath.item % numberOfColumnsInSection; FLSColumnLayoutMetrics *columnMetrics = ...; for (NSInteger item = 0; item < indexPath.item; ++item) { if ([columnMetrics.itemIndexes containsIndex:item]) { /// Shift vertically by items in column } } frame.origin.y = topOffset; CGFloat leftOffset = itemColumn * self.minimumItercolumnSpacing; for (NSInteger column = 0; column < itemColumn; ++column) { /// Shift horizontally by columns left } /// Centre cell in item’s column return frame; }
  • 18. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1
  • 19. Layout invalidation @interface FLSCollectionViewLayoutInvalidationContext : UICollectionViewLayoutInvalidationContext @property (nonatomic, assign) BOOL invalidateLayoutMetrics; @end + (Class)invalidationContextClass; - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds; - (UICollectionViewLayoutInvalidationContext *) invalidationContextForBoundsChange:(CGRect)newBounds; - (void)invalidateLayoutWithContext: (FLSCollectionViewLayoutInvalidationContext *)context;
  • 20. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1
  • 21. Drag and drop • Consider to use gestures controller or state machine • Layout is responsible for changing frame of a dragging item • Data source is responsible for handling motion actions (like reorder array, etc.) General ideas
  • 22. Drag and drop - (void)beginDraggingItemAtIndexPath:(NSIndexPath *)indexPath { /// Snapshot cell and index path self.draggingIndexPath = indexPath; UICollectionViewCell *cell = ...; UIView *snapshot = [cell snapshotViewAfterScreenUpdates:NO]; self.draggingView = snapshot; [self.collectionView addSubview:self.draggingView]; /// Calculate drag bounds if needed [UIView animateWithDuration:animationDuration animations:^{ /// Indicate dragging item with animation } completion:^(BOOL finished) { /// Invalidate layout }]; } Begin dragging
  • 23. Drag and drop - (void)handlePanGesture:(UIPanGestureRecognizer *)gesture { switch (gesture.state) { case UIGestureRecognizerStateChanged:{ [self scheduleDraggingHoldTimer]; /// Calculate new centre of the dragging view CGPoint translation = [gesture translationInView:self.collectionView]; CGPoint diff = ...; self.lastTranslation = translation; CGPoint center = ...; [self constrainPointToDragBounds:&center]; self.draggingView.center = center; /// Trigger autoscroll break; } case UIGestureRecognizerStateEnded: /// Invalidate timers break; } } Handle pan gesture
  • 24. Drag and drop - (void)handleDraggindHold:(NSTimer *)timer { FLSDataSource *dataSource = self.collectionView.dataSource; NSIndexPath *newIndexPath = [self.collectionView indexPathForItemAtPoint:self.draggingView.center]; if (newIndexPath != nil && ![newIndexPath isEqual:self.draggingIndexPath]) { BOOL canMove = ...; /// Use data source if (canMove) { self.draggingIndexPath = newIndexPath; [dataSource collectionView:self.collectionView moveItemAtIndexPath:self.lastSourceIndexPath toIndexPath:newIndexPath isHeld:YES]; self.lastSourceIndexPath = newIndexPath; /// Invalidate layout } } } Handle hold
  • 25. Documents application • Landscape and portrait items A4 scale • Multiple waterfall columns for iPad and iPhone • Number of columns must be changed on device rotation • Drag and drop items like on home screen • Autoscroll while dragging v 0.1
  • 26. Autoscroll • Consider to use CADisplayLink instead of NSTimer • Invalidate dragging hold timer while autoscrolling • Calculate autoscroll direction and velocity while dragging • Calculate dragging view’s frame and collection view’s contentOffset
  • 27. Autoscroll CGRect autoscrollFrame = UIEdgeInsetsInsetRect(self.collectionView.bounds, self.autoscrollTriggerInsets); CGPoint location = [gesture locationInView:self.collectionView]; CGFloat top = CGRectGetMinY(autoscrollFrame); CGFloat bottom = CGRectGetMaxY(autoscrollFrame); if (location.y < top) { self.autosctollVelocity = 10 * (top - location.y); [self scheduleAutoscrollTimerWithDirection:FLSAutoscrollDirectionUp]; } else if (location.y > bottom) { self.autosctollVelocity = 10 * (location.y - bottom); [self scheduleAutoscrollTimerWithDirection:FLSAutoscrollDirectionDown]; } else { [self invalidateAutoscrollTimer]; } Trigger autoscroll
  • 28. Autoscroll CGFloat distance = rintf(self.autosctollVelocity / 60.0); switch (self.autoscrollDirection) { /// Visually stop autoscroll if bottom of the content was reached case FLSAutoscrollDirectionDown: { break; } /// Visually stop autoscroll if top of the content was reached default: break; } CGPoint translation = CGPointMake(0, distance); CGPoint newCenter = ...; [self constrainPointToDragBounds:&newCenter]; self.draggingView.center = newCenter; self.collectionView.contentOffset = ...; Handle autoscroll
  • 29. Recap • Cache all the possible values: calculate once and reuse • Auto layout is your friend • Invalidate layout rationally • Measure, measure and… measure
  • 30. More information WWDC 2014 — Session 232 Advanced User Interfaces with Collection View Source code: https://developer.apple.com/wwdc/resources/sample-code/ WWDC 2014 — Session 226 What's New in Table and Collection Views Collection View Programming Guide for iOS Creating Custom Layout Yalantis Excel Page Layout for Collection View http://yalantis.com/blog/data-grid-with-freeze-columns-play-by-your-rules/ WWDC 2012 — Session 219 Advanced Collection Views and Building Custom Layout 7th iOS Practice Leaders Introduction to Auto Layout Presentation