From 0f594a2af923d24213778b999ceda33464a014b5 Mon Sep 17 00:00:00 2001 From: Oscar Apeland Date: Mon, 23 Oct 2017 16:29:20 +0200 Subject: [PATCH] Initial commit --- SwipingViewController.podspec | 18 + .../project.pbxproj | 90 +++- .../xcdebugger/Breakpoints_v2.xcbkptlist | 25 ++ SwipingViewController/AppDelegate.swift | 42 +- .../AppIcon.appiconset/Contents.json | 5 + .../Base.lproj/Main.storyboard | 24 -- .../ExampleSwipeableViewController.swift | 26 ++ .../ExampleViewController.swift | 66 +++ SwipingViewController/Info.plist | 2 - .../Source/SwipeableCell.swift | 15 + .../Source/SwipeableCell.xib | 43 ++ .../Source/SwipeableCollectionView.swift | 41 ++ .../SwipeableCollectionViewFlowLayout.swift | 30 ++ .../Source/SwipeableItem.swift | 15 + .../Source/SwipeableNavigationBar.swift | 27 ++ .../SwipeableNavigationController.swift | 34 ++ .../Source/SwipeableViewController.swift | 391 ++++++++++++++++++ SwipingViewController/ViewController.swift | 25 -- 18 files changed, 820 insertions(+), 99 deletions(-) create mode 100644 SwipingViewController.podspec create mode 100644 SwipingViewController.xcodeproj/xcuserdata/oscarapeland.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist delete mode 100644 SwipingViewController/Base.lproj/Main.storyboard create mode 100644 SwipingViewController/ExampleSwipeableViewController.swift create mode 100644 SwipingViewController/ExampleViewController.swift create mode 100644 SwipingViewController/Source/SwipeableCell.swift create mode 100644 SwipingViewController/Source/SwipeableCell.xib create mode 100644 SwipingViewController/Source/SwipeableCollectionView.swift create mode 100644 SwipingViewController/Source/SwipeableCollectionViewFlowLayout.swift create mode 100644 SwipingViewController/Source/SwipeableItem.swift create mode 100644 SwipingViewController/Source/SwipeableNavigationBar.swift create mode 100644 SwipingViewController/Source/SwipeableNavigationController.swift create mode 100644 SwipingViewController/Source/SwipeableViewController.swift delete mode 100644 SwipingViewController/ViewController.swift diff --git a/SwipingViewController.podspec b/SwipingViewController.podspec new file mode 100644 index 0000000..0dbe1cb --- /dev/null +++ b/SwipingViewController.podspec @@ -0,0 +1,18 @@ +Pod::Spec.new do |s| +s.name = 'SwipeableViewController' +s.version = '0.1.0' +s.summary = 'A small UI component to build UIPageViewController-y views in your app.' + +s.description = <<-DESC +A segmented header and a UIPageViewController all in one convenient package. +DESC + +s.homepage = 'https://github.com/tiseoslo/SwipeableViewController' +s.license = { :type => 'MIT', :file => 'LICENSE' } +s.author = { 'Oscar Apeland' => 'oscar@tiseit.com' } +s.source = { :git => 'https://github.com/tiseoslo/SwipeableViewController.git', :tag => s.version.to_s } + +s.ios.deployment_target = '10.0' +s.source_files = 'SwipeableViewController/Source/*.swift' + +end diff --git a/SwipingViewController.xcodeproj/project.pbxproj b/SwipingViewController.xcodeproj/project.pbxproj index aa8949a..42653df 100644 --- a/SwipingViewController.xcodeproj/project.pbxproj +++ b/SwipingViewController.xcodeproj/project.pbxproj @@ -8,20 +8,36 @@ /* Begin PBXBuildFile section */ 08254DD81F8E9EDA006DD969 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08254DD71F8E9EDA006DD969 /* AppDelegate.swift */; }; - 08254DDA1F8E9EDA006DD969 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08254DD91F8E9EDA006DD969 /* ViewController.swift */; }; - 08254DDD1F8E9EDA006DD969 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 08254DDB1F8E9EDA006DD969 /* Main.storyboard */; }; 08254DDF1F8E9EDA006DD969 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 08254DDE1F8E9EDA006DD969 /* Assets.xcassets */; }; 08254DE21F8E9EDA006DD969 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 08254DE01F8E9EDA006DD969 /* LaunchScreen.storyboard */; }; + 087E9B1C1F90C336007DCB8F /* ExampleSwipeableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 087E9B1B1F90C336007DCB8F /* ExampleSwipeableViewController.swift */; }; + 08A9E2DB1F9E2FF8000B2729 /* SwipeableNavigationBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D31F9E2FF8000B2729 /* SwipeableNavigationBar.swift */; }; + 08A9E2DC1F9E2FF8000B2729 /* SwipeableItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D41F9E2FF8000B2729 /* SwipeableItem.swift */; }; + 08A9E2DD1F9E2FF8000B2729 /* SwipeableCollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D51F9E2FF8000B2729 /* SwipeableCollectionView.swift */; }; + 08A9E2DE1F9E2FF8000B2729 /* SwipeableCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D61F9E2FF8000B2729 /* SwipeableCell.swift */; }; + 08A9E2DF1F9E2FF8000B2729 /* SwipeableNavigationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D71F9E2FF8000B2729 /* SwipeableNavigationController.swift */; }; + 08A9E2E01F9E2FF8000B2729 /* SwipeableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D81F9E2FF8000B2729 /* SwipeableViewController.swift */; }; + 08A9E2E11F9E2FF8000B2729 /* SwipeableCollectionViewFlowLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9E2D91F9E2FF8000B2729 /* SwipeableCollectionViewFlowLayout.swift */; }; + 08A9E2E21F9E2FF8000B2729 /* SwipeableCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 08A9E2DA1F9E2FF8000B2729 /* SwipeableCell.xib */; }; + 08D04A631F8F959100982B4C /* ExampleViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08D04A621F8F959100982B4C /* ExampleViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 08254DD41F8E9EDA006DD969 /* SwipingViewController.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwipingViewController.app; sourceTree = BUILT_PRODUCTS_DIR; }; 08254DD71F8E9EDA006DD969 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 08254DD91F8E9EDA006DD969 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; - 08254DDC1F8E9EDA006DD969 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 08254DDE1F8E9EDA006DD969 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 08254DE11F8E9EDA006DD969 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 08254DE31F8E9EDA006DD969 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 087E9B1B1F90C336007DCB8F /* ExampleSwipeableViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExampleSwipeableViewController.swift; sourceTree = ""; }; + 08A9E2D31F9E2FF8000B2729 /* SwipeableNavigationBar.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableNavigationBar.swift; sourceTree = ""; }; + 08A9E2D41F9E2FF8000B2729 /* SwipeableItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableItem.swift; sourceTree = ""; }; + 08A9E2D51F9E2FF8000B2729 /* SwipeableCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableCollectionView.swift; sourceTree = ""; }; + 08A9E2D61F9E2FF8000B2729 /* SwipeableCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableCell.swift; sourceTree = ""; }; + 08A9E2D71F9E2FF8000B2729 /* SwipeableNavigationController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableNavigationController.swift; sourceTree = ""; }; + 08A9E2D81F9E2FF8000B2729 /* SwipeableViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableViewController.swift; sourceTree = ""; }; + 08A9E2D91F9E2FF8000B2729 /* SwipeableCollectionViewFlowLayout.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwipeableCollectionViewFlowLayout.swift; sourceTree = ""; }; + 08A9E2DA1F9E2FF8000B2729 /* SwipeableCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SwipeableCell.xib; sourceTree = ""; }; + 08D04A621F8F959100982B4C /* ExampleViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExampleViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -35,6 +51,26 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 080FFF321F9797BE00DF7612 /* Junk */ = { + isa = PBXGroup; + children = ( + 08254DDE1F8E9EDA006DD969 /* Assets.xcassets */, + 08254DE01F8E9EDA006DD969 /* LaunchScreen.storyboard */, + 08254DE31F8E9EDA006DD969 /* Info.plist */, + 08254DD71F8E9EDA006DD969 /* AppDelegate.swift */, + ); + name = Junk; + sourceTree = ""; + }; + 080FFF331F9797CB00DF7612 /* Example */ = { + isa = PBXGroup; + children = ( + 08D04A621F8F959100982B4C /* ExampleViewController.swift */, + 087E9B1B1F90C336007DCB8F /* ExampleSwipeableViewController.swift */, + ); + name = Example; + sourceTree = ""; + }; 08254DCB1F8E9EDA006DD969 = { isa = PBXGroup; children = ( @@ -54,16 +90,28 @@ 08254DD61F8E9EDA006DD969 /* SwipingViewController */ = { isa = PBXGroup; children = ( - 08254DD71F8E9EDA006DD969 /* AppDelegate.swift */, - 08254DD91F8E9EDA006DD969 /* ViewController.swift */, - 08254DDB1F8E9EDA006DD969 /* Main.storyboard */, - 08254DDE1F8E9EDA006DD969 /* Assets.xcassets */, - 08254DE01F8E9EDA006DD969 /* LaunchScreen.storyboard */, - 08254DE31F8E9EDA006DD969 /* Info.plist */, + 08A9E2D21F9E2FF8000B2729 /* Source */, + 080FFF321F9797BE00DF7612 /* Junk */, + 080FFF331F9797CB00DF7612 /* Example */, ); path = SwipingViewController; sourceTree = ""; }; + 08A9E2D21F9E2FF8000B2729 /* Source */ = { + isa = PBXGroup; + children = ( + 08A9E2D31F9E2FF8000B2729 /* SwipeableNavigationBar.swift */, + 08A9E2D41F9E2FF8000B2729 /* SwipeableItem.swift */, + 08A9E2D51F9E2FF8000B2729 /* SwipeableCollectionView.swift */, + 08A9E2D61F9E2FF8000B2729 /* SwipeableCell.swift */, + 08A9E2D71F9E2FF8000B2729 /* SwipeableNavigationController.swift */, + 08A9E2D81F9E2FF8000B2729 /* SwipeableViewController.swift */, + 08A9E2D91F9E2FF8000B2729 /* SwipeableCollectionViewFlowLayout.swift */, + 08A9E2DA1F9E2FF8000B2729 /* SwipeableCell.xib */, + ); + path = Source; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -124,8 +172,8 @@ buildActionMask = 2147483647; files = ( 08254DE21F8E9EDA006DD969 /* LaunchScreen.storyboard in Resources */, + 08A9E2E21F9E2FF8000B2729 /* SwipeableCell.xib in Resources */, 08254DDF1F8E9EDA006DD969 /* Assets.xcassets in Resources */, - 08254DDD1F8E9EDA006DD969 /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -136,22 +184,22 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 08254DDA1F8E9EDA006DD969 /* ViewController.swift in Sources */, + 08A9E2DE1F9E2FF8000B2729 /* SwipeableCell.swift in Sources */, + 08A9E2DC1F9E2FF8000B2729 /* SwipeableItem.swift in Sources */, + 08A9E2E01F9E2FF8000B2729 /* SwipeableViewController.swift in Sources */, + 08A9E2DD1F9E2FF8000B2729 /* SwipeableCollectionView.swift in Sources */, + 08A9E2DF1F9E2FF8000B2729 /* SwipeableNavigationController.swift in Sources */, + 08A9E2E11F9E2FF8000B2729 /* SwipeableCollectionViewFlowLayout.swift in Sources */, + 08A9E2DB1F9E2FF8000B2729 /* SwipeableNavigationBar.swift in Sources */, 08254DD81F8E9EDA006DD969 /* AppDelegate.swift in Sources */, + 08D04A631F8F959100982B4C /* ExampleViewController.swift in Sources */, + 087E9B1C1F90C336007DCB8F /* ExampleSwipeableViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ - 08254DDB1F8E9EDA006DD969 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 08254DDC1F8E9EDA006DD969 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; 08254DE01F8E9EDA006DD969 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( @@ -277,6 +325,7 @@ CODE_SIGN_STYLE = Automatic; DEVELOPMENT_TEAM = 88F3596FP2; INFOPLIST_FILE = SwipingViewController/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = Tise.SwipingViewController; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -292,6 +341,7 @@ CODE_SIGN_STYLE = Automatic; DEVELOPMENT_TEAM = 88F3596FP2; INFOPLIST_FILE = SwipingViewController/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = Tise.SwipingViewController; PRODUCT_NAME = "$(TARGET_NAME)"; diff --git a/SwipingViewController.xcodeproj/xcuserdata/oscarapeland.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/SwipingViewController.xcodeproj/xcuserdata/oscarapeland.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..5e632b8 --- /dev/null +++ b/SwipingViewController.xcodeproj/xcuserdata/oscarapeland.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/SwipingViewController/AppDelegate.swift b/SwipingViewController/AppDelegate.swift index e93455d..73dfc28 100644 --- a/SwipingViewController/AppDelegate.swift +++ b/SwipingViewController/AppDelegate.swift @@ -1,3 +1,4 @@ + // // AppDelegate.swift // SwipingViewController @@ -10,37 +11,22 @@ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - return true - } - - func applicationWillResignActive(_ application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. - } - - func applicationDidEnterBackground(_ application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - } + window = UIWindow(frame: UIScreen.main.bounds) + + let navigationController = SwipeableNavigationController(navigationBarClass: SwipeableNavigationBar.self, toolbarClass: nil) + let viewController = ExampleSwipeableViewController() + viewController.swipeableItems = [SwipeableItem(title: "Recent", viewController: ExampleViewController()), + SwipeableItem(title: "Explore", viewController: ExampleViewController()), + SwipeableItem(title: "Browse", viewController: ExampleViewController())] + viewController.selectedIndex = 1 + navigationController.setViewControllers([viewController], animated: false) + + window?.rootViewController = navigationController + window?.makeKeyAndVisible() - func applicationWillEnterForeground(_ application: UIApplication) { - // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. - } - - func applicationDidBecomeActive(_ application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - } - - func applicationWillTerminate(_ application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + return true } - - } - diff --git a/SwipingViewController/Assets.xcassets/AppIcon.appiconset/Contents.json b/SwipingViewController/Assets.xcassets/AppIcon.appiconset/Contents.json index 1d060ed..d8db8d6 100644 --- a/SwipingViewController/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/SwipingViewController/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -84,6 +84,11 @@ "idiom" : "ipad", "size" : "83.5x83.5", "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" } ], "info" : { diff --git a/SwipingViewController/Base.lproj/Main.storyboard b/SwipingViewController/Base.lproj/Main.storyboard deleted file mode 100644 index 03c13c2..0000000 --- a/SwipingViewController/Base.lproj/Main.storyboard +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/SwipingViewController/ExampleSwipeableViewController.swift b/SwipingViewController/ExampleSwipeableViewController.swift new file mode 100644 index 0000000..544ffd7 --- /dev/null +++ b/SwipingViewController/ExampleSwipeableViewController.swift @@ -0,0 +1,26 @@ +// +// ExampleSwipeableViewController.swift +// SwipingViewController +// +// Created by Oscar Apeland on 13.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +class ExampleSwipeableViewController: SwipeableViewController { + lazy var searchController = UISearchController(searchResultsController: { + $0.view.backgroundColor = .red + return $0 + }(UIViewController())) + + override func viewDidLoad() { + super.viewDidLoad() + if #available(iOS 11.0, *) { + navigationItem.searchController = searchController + } else { + navigationItem.titleView = searchController.searchBar + } + definesPresentationContext = true + } +} diff --git a/SwipingViewController/ExampleViewController.swift b/SwipingViewController/ExampleViewController.swift new file mode 100644 index 0000000..1481289 --- /dev/null +++ b/SwipingViewController/ExampleViewController.swift @@ -0,0 +1,66 @@ +// +// ExampleViewController.swift +// SwipingViewController +// +// Created by Oscar Apeland on 12.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +class ExampleViewController: UIViewController { + lazy var collectionView: UICollectionView = { + $0.backgroundColor = .white + $0.alwaysBounceVertical = true + $0.delegate = self + $0.dataSource = self + $0.autoresizingMask = [.flexibleHeight, .flexibleWidth] + ($0.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) + + return $0 + }(UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout())) + + let cellColor = UIColor.random + + override func viewDidLoad() { + super.viewDidLoad() + view.addSubview(collectionView) + if #available(iOS 11.0, *) { + collectionView.contentInsetAdjustmentBehavior = .always + } + } +} + +extension ExampleViewController: UICollectionViewDataSource, UICollectionViewDelegate { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 100 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) + cell.backgroundColor = cellColor + + return cell + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let vc = UICollectionViewController(collectionViewLayout: UICollectionViewFlowLayout()) + + vc.collectionView?.backgroundColor = .white + vc.collectionView?.dataSource = self + vc.collectionView?.delegate = self + + navigationController?.pushViewController(vc, animated: true) + } +} + +extension UIColor { + class var random: UIColor { + func random() -> CGFloat { + return CGFloat(arc4random()) / CGFloat(UInt32.max) + } + + return UIColor(red: random(), green: random(), blue: random(), alpha: 1.0) + } +} diff --git a/SwipingViewController/Info.plist b/SwipingViewController/Info.plist index 16be3b6..4222ac2 100644 --- a/SwipingViewController/Info.plist +++ b/SwipingViewController/Info.plist @@ -22,8 +22,6 @@ UILaunchStoryboardName LaunchScreen - UIMainStoryboardFile - Main UIRequiredDeviceCapabilities armv7 diff --git a/SwipingViewController/Source/SwipeableCell.swift b/SwipingViewController/Source/SwipeableCell.swift new file mode 100644 index 0000000..ee77c71 --- /dev/null +++ b/SwipingViewController/Source/SwipeableCell.swift @@ -0,0 +1,15 @@ +// +// SwiperCell.swift +// SwiperNavigationBar +// +// Created by Oscar Apeland on 11.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +class SwipeableCell: UICollectionViewCell { + static let id = "SwipeableCell" + + @IBOutlet weak var label: UILabel! +} diff --git a/SwipingViewController/Source/SwipeableCell.xib b/SwipingViewController/Source/SwipeableCell.xib new file mode 100644 index 0000000..cb83ede --- /dev/null +++ b/SwipingViewController/Source/SwipeableCell.xib @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SwipingViewController/Source/SwipeableCollectionView.swift b/SwipingViewController/Source/SwipeableCollectionView.swift new file mode 100644 index 0000000..ea3c50f --- /dev/null +++ b/SwipingViewController/Source/SwipeableCollectionView.swift @@ -0,0 +1,41 @@ +// +// SwipeableCollectionView.swift +// SwipingViewController +// +// Created by Oscar Apeland on 12.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +typealias CollectionViewController = UICollectionViewDelegate & UICollectionViewDataSource + +class SwipeableCollectionView: UICollectionView { + var controller: CollectionViewController? { + didSet { + delegate = controller + dataSource = controller + + if controller !== oldValue { + reloadData() + } + } + } + + override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { + super.init(frame: frame, collectionViewLayout: layout) + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + private func setup() { + backgroundColor = .clear + register(UINib(nibName: SwipeableCell.id, bundle: nil), forCellWithReuseIdentifier: SwipeableCell.id) + alwaysBounceHorizontal = true + showsHorizontalScrollIndicator = false + } +} diff --git a/SwipingViewController/Source/SwipeableCollectionViewFlowLayout.swift b/SwipingViewController/Source/SwipeableCollectionViewFlowLayout.swift new file mode 100644 index 0000000..8882b7b --- /dev/null +++ b/SwipingViewController/Source/SwipeableCollectionViewFlowLayout.swift @@ -0,0 +1,30 @@ +// +// SwipeableCollectionViewFlowLayout.swift +// SwipingViewController +// +// Created by Oscar Apeland on 12.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +class SwipeableCollectionViewFlowLayout: UICollectionViewFlowLayout { + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + private func setup() { + sectionInset = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0) + estimatedItemSize = CGSize(width: 60.0, height: 52.0) + minimumInteritemSpacing = .leastNonzeroMagnitude + minimumLineSpacing = .leastNonzeroMagnitude + scrollDirection = .horizontal + } +} diff --git a/SwipingViewController/Source/SwipeableItem.swift b/SwipingViewController/Source/SwipeableItem.swift new file mode 100644 index 0000000..5c880f3 --- /dev/null +++ b/SwipingViewController/Source/SwipeableItem.swift @@ -0,0 +1,15 @@ +// +// SwipeableItem.swift +// SwipingViewController +// +// Created by Oscar Apeland on 11.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import Foundation +import UIKit + +struct SwipeableItem { + var title: String + var viewController: UIViewController +} diff --git a/SwipingViewController/Source/SwipeableNavigationBar.swift b/SwipingViewController/Source/SwipeableNavigationBar.swift new file mode 100644 index 0000000..3e48927 --- /dev/null +++ b/SwipingViewController/Source/SwipeableNavigationBar.swift @@ -0,0 +1,27 @@ +// +// SwipeableNavigationBar.swift +// SwipingViewController +// +// Created by Oscar Apeland on 12.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +public class SwipeableNavigationBar: UINavigationBar { + // MARK: Properties + lazy var largeTitleView: UIView? = { + return subviews.first { String(describing: type(of: $0)) == "_UINavigationBarLargeTitleView" } + }() + + var largeTitleLabel: UILabel? { + return largeTitleView?.subviews.first { $0 is UILabel } as? UILabel + } + + lazy var collectionView: SwipeableCollectionView = { + $0.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] + + return $0 + }(SwipeableCollectionView(frame: largeTitleView!.bounds, + collectionViewLayout: SwipeableCollectionViewFlowLayout())) +} diff --git a/SwipingViewController/Source/SwipeableNavigationController.swift b/SwipingViewController/Source/SwipeableNavigationController.swift new file mode 100644 index 0000000..00c44d9 --- /dev/null +++ b/SwipingViewController/Source/SwipeableNavigationController.swift @@ -0,0 +1,34 @@ +// +// SwipeableNavigationController.swift +// SwipingViewController +// +// Created by Oscar Apeland on 12.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +public class SwipeableNavigationController: UINavigationController { + override public func viewDidLoad() { + super.viewDidLoad() + guard navigationBar is SwipeableNavigationBar else { + fatalError("navigationBar must be of class SwipeableNavigationBar") + } + + delegate = self + } +} + +extension SwipeableNavigationController: UINavigationControllerDelegate { + public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { + if #available(iOS 11.0, *) { + navigationController.navigationBar.prefersLargeTitles = viewController is SwipeableViewController + } + } + + public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { + if #available(iOS 11.0, *) { + navigationController.navigationBar.prefersLargeTitles = viewController is SwipeableViewController + } + } +} diff --git a/SwipingViewController/Source/SwipeableViewController.swift b/SwipingViewController/Source/SwipeableViewController.swift new file mode 100644 index 0000000..ef24807 --- /dev/null +++ b/SwipingViewController/Source/SwipeableViewController.swift @@ -0,0 +1,391 @@ +// +// ViewController.swift +// SwipingViewController +// +// Created by Oscar Apeland on 11.10.2017. +// Copyright © 2017 Tise. All rights reserved. +// + +import UIKit + +/** + Pattern: Massive View Controller + + Notes: + */ +enum PanDirection { + case rightToLeft, leftToRight + + static func directionFor(velocity: CGPoint) -> PanDirection { + return velocity.x < 0 ? .rightToLeft : leftToRight + } +} + +public class SwipeableViewController: UIViewController { + // MARK: Swipeable properties + var swipeableItems: [SwipeableItem] = [] + var selectedIndex: Int! + + // MARK: UI properties + private lazy var panGestureRecognizer: UIPanGestureRecognizer = { + $0.delegate = self + return $0 + }(UIPanGestureRecognizer(target: self, action: #selector(viewPanned(_:)))) + + private var navigationBar: SwipeableNavigationBar! { + return navigationController!.navigationBar as! SwipeableNavigationBar + } + + var collectionView: SwipeableCollectionView? { + if #available(iOS 11, *) { + return navigationBar.collectionView + } else { + return swipeableCollectionView + } + } + + lazy var swipeableCollectionView: SwipeableCollectionView = { + return SwipeableCollectionView(frame: CGRect(x: 0, y: 64.0, width: view.bounds.width, height: 52.1), + collectionViewLayout: SwipeableCollectionViewFlowLayout()) + }() + + // MARK: Life cycle + override public func viewDidLoad() { + super.viewDidLoad() + + // Safeguards + guard !swipeableItems.isEmpty else { + fatalError("swipableItems is empty.") + } + + guard 0...swipeableItems.count ~= selectedIndex else { + fatalError("startIndex out of range.") + } + + // Setup - Custom transitions + let initialItem = swipeableItems[selectedIndex] + view.addGestureRecognizer(panGestureRecognizer) + + // Setup - Navigation bar + navigationItem.title = initialItem.title + if #available(iOS 11.0, *) { + navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.clear] + } + + // Setup - View + view.backgroundColor = .white + + + // On iOS <11 we add the collectionView underneath the navigation bar instead of inside. + // Negative OS check currently impossible + if #available(iOS 11, *) {} + else { + swipeableCollectionView.translatesAutoresizingMaskIntoConstraints = false + automaticallyAdjustsScrollViewInsets = false + + view.addSubview(swipeableCollectionView) + + NSLayoutConstraint.activate([collectionView!.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 64.0), + collectionView!.heightAnchor.constraint(equalToConstant: 52.1), + collectionView!.trailingAnchor.constraint(equalTo: view.trailingAnchor), + collectionView!.leadingAnchor.constraint(equalTo: view.leadingAnchor)]) + } + + add(childViewController: initialItem.viewController) + } + + override public func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + if #available(iOS 11, *) { + if let titleView = navigationBar.largeTitleView, titleView.subviews.filter ({ $0 is UICollectionView }).isEmpty { + navigationBar.largeTitleView!.addSubview(navigationBar.collectionView) + } + } + + collectionView?.controller = self + } + + // MARK: Convenience + /// Convenience methods for swapping out two child view controllers without animation. + private func switchChildViewController(from fromVc: UIViewController, to toVc: UIViewController) { + remove(childViewController: fromVc) + add(childViewController: toVc) + } + + private func remove(childViewController: UIViewController) { + childViewController.willMove(toParentViewController: nil) + childViewController.view.removeFromSuperview() + childViewController.removeFromParentViewController() + } + + /** + Do all the required UIKit calls for adding a child view controller. + - parameter childViewController: The controller to add. + - returns: The view of the added view controller. + */ + @discardableResult + private func add(childViewController: UIViewController) -> UIView { + childViewController.willMove(toParentViewController: self) + addChildViewController(childViewController) + view.addSubview(childViewController.view) + childViewController.didMove(toParentViewController: self) + + if #available(iOS 11, *) {} + else { + childViewController.view.translatesAutoresizingMaskIntoConstraints = false + childViewController.view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) + + NSLayoutConstraint.activate([childViewController.view.topAnchor.constraint(equalTo: collectionView!.bottomAnchor), + childViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + childViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + childViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor)]) + } + + return childViewController.view + } + + /// The view controller after the current child view controller, if there is any. + func nextViewController() -> UIViewController? { + let nextIndex = selectedIndex + 1 + return swipeableItems.indices.contains(nextIndex) ? swipeableItems[nextIndex].viewController : nil + } + + /// The view controller before the current child view controller, if there is any. + func previousViewController() -> UIViewController? { + let previousIndex = selectedIndex - 1 + return swipeableItems.indices.contains(previousIndex) ? swipeableItems[previousIndex].viewController : nil + } + + // MARK: Animation + private var startPoint: CGPoint? + private var startDirection: PanDirection? + private var animationProgress: CGFloat = 0.0 + private weak var animatingViewController: UIViewController? + private var didForceCancel = false + + var prevState: UIGestureRecognizerState! + + @objc + func viewPanned(_ gesture: UIPanGestureRecognizer) { + let velocity = gesture.velocity(in: gesture.view) + let direction = PanDirection.directionFor(velocity: velocity) + + if gesture.state != prevState { + print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, gesture) + prevState = gesture.state + } + + // Animate + switch gesture.state { + case .began: + // If there's nothing to show, cancel the gesture + guard let viewController = (direction == .rightToLeft) ? nextViewController() : previousViewController() else { + didForceCancel = true + gesture.isEnabled = false; gesture.isEnabled = true + return + } + + // Add the view offscreen + add(childViewController: viewController) + + // Keep for animation + startPoint = gesture.location(in: view!) + startDirection = direction + animatingViewController = viewController + + // Render the layer offscreen + switch startDirection! { + case .leftToRight: viewController.view.transform = CGAffineTransform(translationX: -view.bounds.width, y: 0) + case .rightToLeft: viewController.view.transform = CGAffineTransform(translationX: view.bounds.width, y: 0) + } + + case .changed: + let location = gesture.location(in: view!) + let relativeLocation = location.x - startPoint!.x + + // If we have swiped beyond the initial touch point, cancel the animation. + // Switching isEnabled calls .cancelled which resets the transition before it calls .began which will restart it in the other direction + if (location.x > startPoint!.x && startDirection! == .rightToLeft) || (location.x < startPoint!.x && startDirection! == .leftToRight) { + self.endAnimation() + gesture.isEnabled = false; gesture.isEnabled = true + return + } + + switch startDirection! { + case .leftToRight: + animatingViewController!.view.transform = CGAffineTransform(translationX: relativeLocation - view.frame.width, y: 0) + swipeableItems[selectedIndex].viewController.view.transform = CGAffineTransform(translationX: relativeLocation, y: 0) + + case .rightToLeft: + animatingViewController!.view.transform = CGAffineTransform(translationX: relativeLocation + view.frame.width, y: 0) + swipeableItems[selectedIndex].viewController.view.transform = CGAffineTransform(translationX: relativeLocation, y: 0) + } + + case .ended, .cancelled: + // If we cancel the gesture in .began, return because all ivars are nil and there's nothing to cancel. + guard !didForceCancel else { + didForceCancel = false + return + } + + guard let startPoint = startPoint, let startDirection = startDirection, let animatingViewController = animatingViewController else { + print("ffffff") + return + } + + let location = gesture.location(in: view!) + let relativeLocation = location.x - startPoint.x + + let completionTreshold: CGFloat = 0.7 + let velocityTreshold: CGFloat = 1000.0 + + var isDone = false + var swipeDistance: CGFloat = 0.0 + + // Decide if we are done + switch startDirection { + case .leftToRight: + swipeDistance = view.frame.width - startPoint.x + let progress = relativeLocation / swipeDistance // 0...1, not 1...100 + + // print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, "LtR", progress, velocity.x, progress > 0.5 || velocity.x > 1000 ? "Done" : "Not done") + isDone = progress > completionTreshold || velocity.x > velocityTreshold + + case .rightToLeft: + swipeDistance = startPoint.x + let progress = relativeLocation / swipeDistance + + // print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, "RtL", progress, velocity.x, fabs(progress) > 0.5 || velocity.x < -1000 ? "Done" : "Not done") + isDone = fabs(progress) > completionTreshold || velocity.x < -velocityTreshold + } + + + // Complete animation and clean up + if isDone { + // Complete the animation + UIView.animate(withDuration: 0.25, delay: 0.0, + options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], + animations: { + animatingViewController.view.transform = .identity + let previousView = self.swipeableItems[self.selectedIndex].viewController.view! + let translationX = (self.startDirection == .leftToRight) ? previousView.frame.width : -previousView.frame.width + previousView.transform = CGAffineTransform(translationX: translationX, y: 0) + }, completion: { (isFinished) in + print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, "Complete animation \(isFinished ? "FINISHED" : "CANCELLED")") + + self.remove(childViewController: self.swipeableItems[self.selectedIndex].viewController) + self.endAnimation() + + let nextIndex = self.selectedIndex + (direction == .leftToRight ? -1 : +1) + let previousIndexPath = IndexPath(item: self.selectedIndex, section: 0) + let nextIndexPath = IndexPath(item: nextIndex, section: 0) + + (self.collectionView?.cellForItem(at: previousIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) + (self.collectionView?.cellForItem(at: nextIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) + + self.selectedIndex = nextIndex + self.navigationItem.title = self.swipeableItems[self.selectedIndex].title + self.collectionView!.selectItem(at: IndexPath(item: self.selectedIndex, section: 0), animated: true, scrollPosition: .centeredHorizontally) + }) + } else { + //Cancel the animation + UIView.animate(withDuration: 0.25, delay: 0.0, + options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], + animations: { + self.swipeableItems[self.selectedIndex].viewController.view!.transform = .identity + let previousView = self.animatingViewController!.view! + let translationX = (self.startDirection! == .leftToRight) ? -previousView.frame.width : previousView.frame.width + previousView.transform = CGAffineTransform(translationX: translationX, y: 0) + }, completion: { (isFinished) in + print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, "Cancel animation \(isFinished ? "FINISHED" : "CANCELLED")") + self.remove(childViewController: self.animatingViewController!) + self.endAnimation() + }) + } + + default: + break + } + } + + private func endAnimation() { + startPoint = nil + startDirection = nil + animationProgress = 0 + } + + func swipeTo(index nextIndex: Int) { + guard swipeableItems.indices.contains(nextIndex) else { + return + } + + let direction: PanDirection = nextIndex > selectedIndex ? .leftToRight : .rightToLeft + + let lowerBound = min(selectedIndex, nextIndex) + let upperBound = max(selectedIndex, nextIndex) + var viewControllers = swipeableItems[lowerBound...upperBound].map { $0.viewController } + + if direction == .rightToLeft { + viewControllers.reverse() + } + + for (index, viewController) in viewControllers.enumerated() { + self.add(childViewController: viewController) + let offsetX: CGFloat = (direction == .leftToRight) ? viewController.view.frame.width : -viewController.view.frame.width + viewController.view.transform = CGAffineTransform(translationX: CGFloat(index) * offsetX, y: 0) + } + + UIView.animate(withDuration: 0.25, delay: 0.0, + options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], + animations: { + for (reversedIndex, viewController) in viewControllers.reversed().enumerated() { + let offsetX: CGFloat = (direction == .leftToRight) ? -viewController.view.frame.width : viewController.view.frame.width + viewController.view.transform = CGAffineTransform(translationX: CGFloat(reversedIndex) * offsetX, y: 0) + } + }) { (isFinished) in + viewControllers.dropLast().forEach(self.remove) + + let previousIndexPath = IndexPath(item: self.selectedIndex, section: 0) + let nextIndexPath = IndexPath(item: nextIndex, section: 0) + + (self.collectionView?.cellForItem(at: previousIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) + (self.collectionView?.cellForItem(at: nextIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) + + self.selectedIndex = nextIndex + self.navigationItem.title = self.swipeableItems[self.selectedIndex].title + self.collectionView!.selectItem(at: IndexPath(item: self.selectedIndex, section: 0), animated: true, scrollPosition: .centeredHorizontally) + } + } +} + +extension SwipeableViewController: UICollectionViewDataSource, UICollectionViewDelegate { + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + print(#file.components(separatedBy: "/").last!,":",#line,"-",#function, swipeableItems.count) + return swipeableItems.count + } + + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SwipeableCell.id, for: indexPath) as? SwipeableCell else { + fatalError() + } + + cell.label.text = swipeableItems[indexPath.row].title + cell.label.textColor = indexPath.row == selectedIndex ? #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) : #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) + + return cell + } + + public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + swipeTo(index: indexPath.row) + } +} + +extension SwipeableViewController: UIGestureRecognizerDelegate { + public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if let pan = gestureRecognizer as? UIPanGestureRecognizer { + let velocity = pan.velocity(in: view) + return fabs(velocity.x) > fabs(velocity.y) + } + return true + } +} diff --git a/SwipingViewController/ViewController.swift b/SwipingViewController/ViewController.swift deleted file mode 100644 index 16bd5c6..0000000 --- a/SwipingViewController/ViewController.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// ViewController.swift -// SwipingViewController -// -// Created by Oscar Apeland on 11.10.2017. -// Copyright © 2017 Tise. All rights reserved. -// - -import UIKit - -class ViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib. - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - -} -