From 250f92970ae458cb4ece73b85c18e26044a123c0 Mon Sep 17 00:00:00 2001 From: Sam Stigler Date: Sun, 9 Oct 2016 17:19:12 -0500 Subject: [PATCH 1/2] Works around crash seen when using layout with AsyncDisplayKit. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AsyncDisplayKit was requesting a layout before the collection view had items (or sections). That led to a crash because the `numberOfItems` computed property was querying the collection view for the number of items in non-existent section 0. This fix updates the `numberOfItems` computed property to always return 0 if there aren’t any sections in the collection view. --- Source/SFFocusViewLayout.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source/SFFocusViewLayout.swift b/Source/SFFocusViewLayout.swift index d5f59dc..a223360 100644 --- a/Source/SFFocusViewLayout.swift +++ b/Source/SFFocusViewLayout.swift @@ -126,6 +126,10 @@ public class SFFocusViewLayout: UICollectionViewLayout { private extension UICollectionViewLayout { var numberOfItems: Int { + guard collectionView?.numberOfSections() > 0 else { + return 0 + } + return collectionView!.numberOfItemsInSection(0) } From cff2cfd8433eed9537001c9be14c07a606ec9b9e Mon Sep 17 00:00:00 2001 From: Sam Stigler Date: Sun, 9 Oct 2016 17:25:14 -0500 Subject: [PATCH 2/2] Adds test for zero-sections fix. --- Tests/CollectionViewController.swift | 4 +++- Tests/Tests.swift | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Tests/CollectionViewController.swift b/Tests/CollectionViewController.swift index f3a093e..ae6100a 100644 --- a/Tests/CollectionViewController.swift +++ b/Tests/CollectionViewController.swift @@ -13,6 +13,8 @@ private let reuseIdentifier = "Cell" class CollectionViewController: UICollectionViewController { var items = [Int]() + + var numberOfSectionsToReturn = 1 override func viewDidLoad() { super.viewDidLoad() @@ -23,7 +25,7 @@ class CollectionViewController: UICollectionViewController { // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { - return 1 + return numberOfSectionsToReturn } diff --git a/Tests/Tests.swift b/Tests/Tests.swift index 75a8a26..e8088c5 100644 --- a/Tests/Tests.swift +++ b/Tests/Tests.swift @@ -81,5 +81,10 @@ class Tests: XCTestCase { func testLayoutShouldInvalidateLayoutForBoundsChange() { XCTAssertTrue(focusViewLayout.shouldInvalidateLayoutForBoundsChange(CGRect())) } + + func testCanPrepareLayoutForCollectionViewWithZeroSections() { + collectionViewController?.numberOfSectionsToReturn = 0 + focusViewLayout.prepareLayout() + } }