{"id":2861,"url":"https://github.com/Yalantis/DisplaySwitcher","last_synced_at":"2025-08-03T12:31:27.369Z","repository":{"id":48656918,"uuid":"55959044","full_name":"Yalantis/DisplaySwitcher","owner":"Yalantis","description":"Custom transition between two collection view layouts","archived":false,"fork":false,"pushed_at":"2021-07-15T14:13:46.000Z","size":9667,"stargazers_count":2324,"open_issues_count":13,"forks_count":190,"subscribers_count":64,"default_branch":"master","last_synced_at":"2024-10-29T17:56:00.109Z","etag":null,"topics":["animation","cocoapods","custom-layout","custom-transitions","display-switcher","ios","swift","transition-layout","yalantis"],"latest_commit_sha":null,"homepage":"https://yalantis.com","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Yalantis.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/contributing.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-04-11T09:27:42.000Z","updated_at":"2024-10-22T12:56:41.000Z","dependencies_parsed_at":"2022-08-21T03:50:23.285Z","dependency_job_id":null,"html_url":"https://github.com/Yalantis/DisplaySwitcher","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yalantis%2FDisplaySwitcher","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yalantis%2FDisplaySwitcher/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yalantis%2FDisplaySwitcher/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Yalantis%2FDisplaySwitcher/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Yalantis","download_url":"https://codeload.github.com/Yalantis/DisplaySwitcher/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228461247,"owners_count":17923761,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["animation","cocoapods","custom-layout","custom-transitions","display-switcher","ios","swift","transition-layout","yalantis"],"created_at":"2024-01-05T20:16:24.764Z","updated_at":"2024-12-07T00:31:02.240Z","avatar_url":"https://github.com/Yalantis.png","language":"Swift","funding_links":[],"categories":["UI","Swift"],"sub_categories":["Table View / Collection View","Layout","Other free courses"],"readme":"# Display Switcher\n\n[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/DisplaySwitcher.svg)](https://img.shields.io/cocoapods/v/DisplaySwitcher.svg)\n[![Platform](http://img.shields.io/badge/platform-iOS-blue.svg?style=flat)](http://cocoapods.org/?q=YALSideMenu) \n[![License](http://img.shields.io/badge/license-MIT-green.svg?style=flat)]() \n[![Yalantis](https://raw.githubusercontent.com/Yalantis/PullToRefresh/develop/PullToRefreshDemo/Resources/badge_dark.png)](https://yalantis.com/?utm_source=github)\n\nWe designed a UI that allows users to switch between list and grid views on the fly and choose the most convenient display type. List view usually provides more details about each user or contact. Grid view allows more users or contacts to appear on the screen at the same time.\n \nWe created design mockups for both list and grid views using Sketch. As soon as the mockups were ready, we used Principle to create a smooth transition between the two display types. Note that the hamburger menu changes its appearance depending on which view is activated:\n\n![Preview](https://github.com/Yalantis/DisplaySwitcher/blob/master/Assets/animation.gif)\n\n## Requirements\n- iOS 10.0+\n- Xcode 11\n- Swift 5\n\n## Installing \n\n### [CocoaPods](https://cocoapods.org)\n\n```ruby\nuse_frameworks!\npod ‘DisplaySwitcher’, '~\u003e 2.0’\n```\n\n### [Carthage](https://github.com/Carthage/Carthage)\n\n```\ngithub \"Yalantis/DisplaySwitcher\" \"master\"\n```\n\n## Use Cases\nYou can use our Contact Display Switch for:\n\n- Social networking apps\n- Dating apps\n- Email clients\n- Any other app that features list of friends or contacts\n \nOur DisplaySwitcher component isn't limited to friends and contacts lists. It can work with any other content too.\n\n## Usage\n\nAt first, import DisplaySwitcher:\n\n```swift\nimport DisplaySwitcher\n```\n\nThen create two layouts (list mode and grid mode):\n\n```swift\nprivate lazy var listLayout = DisplaySwitchLayout(staticCellHeight: listLayoutStaticCellHeight, nextLayoutStaticCellHeight: gridLayoutStaticCellHeight, layoutState: .list)\n\nprivate lazy var gridLayout = DisplaySwitchLayout(staticCellHeight: gridLayoutStaticCellHeight, nextLayoutStaticCellHeight: listLayoutStaticCellHeight, layoutState: .grid)\n```\n\nSet current layout:\n\n```swift\nprivate var layoutState: LayoutState = .list\ncollectionView.collectionViewLayout = listLayout\n```\n\nThen override two UICollectionViewDataSource methods:\n\n```swift\nfunc collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -\u003e Int {\n    // count of items\n}\n\nfunc collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -\u003e UICollectionViewCell {\n    // configure your custom cell\n}\n```\n\nAlso override one UICollectionViewDelegate method (for custom layout transition):\n\n```swift\nfunc collectionView(collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -\u003e UICollectionViewTransitionLayout {\n    let customTransitionLayout = TransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)\n    return customTransitionLayout\n}\n```\n\nAnd in the end necessary create transition and start it (you can simply change animation duration for transition layout and for rotation button):\n\n```swift\nlet transitionManager: TransitionManager\nif layoutState == .list {\n    layoutState = .grid\n    transitionManager = TransitionManager(duration: animationDuration, collectionView: collectionView!, destinationLayout: gridLayout, layoutState: layoutState)\n} else {\n    layoutState = .list\n    transitionManager = TransitionManager(duration: animationDuration, collectionView: collectionView!, destinationLayout: listLayout, layoutState: layoutState)\n}\ntransitionManager.startInteractiveTransition()\nrotationButton.selected = layoutState == .list\nrotationButton.animationDuration = animationDuration\n```\n\n## Under the hood\nWe use five classes to implement our DisplaySwitcher:\n\n### BaseLayout\nIn the BaseLayout class, we use methods for building list and grid layouts. But what’s most interesting here is the сontentOffset calculation that should be defined after the transition to a new layout.\n \nFirst, save the сontentOffset of the layout you are switching from:\n\n```swift\n override func prepareForTransitionFromLayout(oldLayout: UICollectionViewLayout) {\n       previousContentOffset = NSValue(CGPoint:collectionView!.contentOffset)  \n       return super.prepareForTransitionFromLayout(oldLayout)\n\n   }\n``` \nThen, calculate the сontentOffset for the new layout in the targetContentOffsetForProposedContentOffset method:\n\n```swift\noverride func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint) -\u003e CGPoint {\n       let previousContentOffsetPoint = previousContentOffset?.CGPointValue()\n       let superContentOffset = super.targetContentOffsetForProposedContentOffset(proposedContentOffset)\n       if let previousContentOffsetPoint = previousContentOffsetPoint {\n           if previousContentOffsetPoint.y == 0 {\n               return previousContentOffsetPoint\n           }\n           if layoutState == CollectionViewLayoutState.ListLayoutState {\n               let offsetY = ceil(previousContentOffsetPoint.y + (staticCellHeight * previousContentOffsetPoint.y / nextLayoutStaticCellHeight) + cellPadding)\n               return CGPoint(x: superContentOffset.x, y: offsetY)\n           } else {\n               let realOffsetY = ceil((previousContentOffsetPoint.y / nextLayoutStaticCellHeight * staticCellHeight / CGFloat(numberOfColumns)) - cellPadding)\n               let offsetY = floor(realOffsetY / staticCellHeight) * staticCellHeight + cellPadding\nreturn CGPoint(x: superContentOffset.x, y: offsetY)\n           }\n       }\n       return superContentOffset\n   }\n``` \n \nAnd then clear value of variable in method finalizeLayoutTransition:\n\n```swift\noverride func finalizeLayoutTransition() {\n       previousContentOffset = nil\n       super.finalizeLayoutTransition()\n   }\n``` \n \n### BaseLayoutAttributes\n\nIn the BaseLayoutAttributes class, a few custom attributes are added:\n\n```swift\nvar transitionProgress: CGFloat = 0.0\n   var nextLayoutCellFrame = CGRectZero\n   var layoutState: CollectionViewLayoutState = .ListLayoutState\n``` \n\ntransitionProgress is the current value of the animation transition that varies between 0 and 1. It’s needed for calculating constraints in the cell.\n \nnextLayoutCellFrame is a property that returns the frame of the layout you switch to. It’s also used for the cell layout configuration during the process of transition.\n \nlayoutState is the current state of the layout.\n\n### TransitionLayout\n\nThe TransitionLayout class overrides two UICollectionViewLayout methods:\n \nlayoutAttributesForElementsInRect and   \nlayoutAttributesForItemAtIndexPath, where we set properties values for the class BaseLayoutAttributes.\n\n### TransitionManager\nThe TransitionManager class uses the UICollectionView’sstartInteractiveTransitionToCollectionViewLayout method, where you point the layout it must switch to:\n\n```swift\nfunc startInteractiveTransition() {\n       UIApplication.sharedApplication().beginIgnoringInteractionEvents()\n       transitionLayout = collectionView.startInteractiveTransitionToCollectionViewLayout(destinationLayout, completion: { success, finish in\n           if success \u0026\u0026 finish {\n               self.collectionView.reloadData()\n               UIApplication.sharedApplication().endIgnoringInteractionEvents()\n           }\n       }) as! TransitionLayout\n       transitionLayout.layoutState = layoutState\n       createUpdaterAndStart()\n   }\n``` \n \n### CADisplayLink class\n \nThis class is used to control animation duration. This class helps calculate the animation progress depending on the animation duration preset:\n \n```swift\nprivate func createUpdaterAndStart() {\n       start = CACurrentMediaTime()\n       updater = CADisplayLink(target: self, selector: Selector(\"updateTransitionProgress\"))\n       updater.frameInterval = 1\n       updater.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)\n   }\n\ndynamic func updateTransitionProgress() {\n       var progress = (updater.timestamp - start) / duration\n       progress = min(1, progress)\n       progress = max(0, progress)\n       transitionLayout.transitionProgress = CGFloat(progress)\n\n       transitionLayout.invalidateLayout()\n       if progress == finishTransitionValue {\n           collectionView.finishInteractiveTransition()\n           updater.invalidate()\n       }\n   }\n```\n\nThat’s it! Use our DisplaySwitcher in any way you like! Check it out on [Dribbble](https://dribbble.com/shots/2276068-Contact-Display-Switch).\n\n#### Let us know!\n\nWe’d be really happy if you sent us links to your projects where you use our component. Just send an email to github@yalantis.com And do let us know if you have any questions or suggestion regarding the animation. \n\nP.S. We’re going to publish more awesomeness wrapped in code and a tutorial on how to make UI for iOS (Android) better than better. Stay tuned!\n\n## License\n\nThe MIT License (MIT)\n\nCopyright © 2017 Yalantis\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYalantis%2FDisplaySwitcher","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FYalantis%2FDisplaySwitcher","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYalantis%2FDisplaySwitcher/lists"}