Git Product home page Git Product logo

literoute's Introduction

LiteRoute

Build Status Pod version Carthage compatible Platform License Twitter Swift

Description

LiteRoute is easy transition between VIPER modules, who implemented on pure Swift. We can transition between your modules very easy from couple lines of codes.

What's happend with LightRoute?

Because CocoaPods Dev Team doesn't respond me about return right to my lib, I will move LightRoute to other name LiteRoute. Code and all rights saved.

Installation

CocoaPods

Add to your podfile:

pod "LiteRoute"

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate LiteRoute into your Xcode project using Carthage, specify it in your Cartfile:

github "SpectralDragon/LiteRoute" ~> 2.1

Run carthage update to build the framework and drag the built LiteRoute.framework into your Xcode project.

Swift Package Manager

Once you have your Swift package set up, adding LiteRoute as a dependency is as easy as adding it to the dependencies value of your Package.swift.

Swift 4

dependencies: [
    .package(url: "https://github.com/SpectralDragon/LiteRoute.git", from: "2.1")
]

Example

About LiteRoute

LiteRoute can work with Segue, UINavigationController and default view controller presenting.

For all transition, returns TransitionNode instance, who managed current transition. You can change transition flow, how you want.

How to use

For example, we will make the transition between the two VIPER modules:

import LiteRoute

// MARK: - The module initiating the transition.

protocol FirstViperRouterInput: class {
  func openModule(userIdentifier: String)
}

final class FirstViperRouter: FirstViperRouterInput {

  // This property contain protocol protected view controller for transition.
  weak var transitionHandler: TransitionHandler!

  // View controller identifier for current storyboard.
  let viewControllerIdentifier = "SecondViperViewController"


  func openModule(userIdentifier: String) {

      try? transitionHandler
				
      // Initiates the opening of a new view controller.
      .forCurrentStoryboard(resterationId: viewControllerIdentifier, to: SecondViperViewControllerModuleInput.self)
				
      // Set animate for transition.
      .transition(animate: false)

      // Set transition case.
      .to(preffered: TransitionStyle.navigation(style: .push))

      // View controller init block. 
      .then { moduleInput in 
        moduleInput.configure(with: userIdentifier)
      }
  }
} 

// MARK: - The module at which the jump occurs.

// Module input protocol for initialize
protocol SecondViperViewControllerModuleInput: class {
  func configure(with userIdentifier: String)
}


final class SecondViperPresenter: SecondViperViewControllerModuleInput, ... {
	
  // Implementation protocol
  func configure(with userIdentifier: String) {
		print("User identifier", userIdentifier) // Print it!
    // Initialize code..
  }

}

In this case, you make default transition between viewControllers and configure moduleInput how you want. But also, you can use just viewController, example:

.forCurrentStoryboard(resterationId: viewControllerIdentifier, to: SecondViperPresenter.self)
/// and etc..

Note❗️ moduleInput - by default that property contain your output property in destination view controller. You can change that use methods selector:. You can use next for get custom moduleInput:

  • by string: selector(_ selector: String)
  • by selector: selector(_ selector: Selector)
  • by keyPath: selector(_ selector: KeyPath)

Transition case

For example we analyze this code, then contain two case for work with transition:

First case:

This default case, with default LiteRoute implementation. If you want just present new module, then use that:

try? transitionHandler

// Initiates the opening of a new view controller.
.forCurrentStoryboard(resterationId: viewControllerIdentifier, to: SecondViperViewControllerModuleInput.self)

// Setup module input.
.then { moduleInput in 
  moduleInput.configure(with: "Hello!")
}

Second case:

But first way can't be flexible, for that has customTransition() method. This method returns CustomTransitionNode. This node not support default TransitionNode methods. CustomTransitionNode is class, who return method flexible settings your transition, but for this transition flow, you should be implement your transition logic, and call them(_:) or perform() method for activate transition.

Example:

try? transitionHandler

// Initiates the opening of a new view controller.
.forCurrentStoryboard(resterationId: viewControllerIdentifier, to: SecondViperViewControllerModuleInput.self)

// Activate custom transition.
.customTransition()

// Custom transition case.
.transition { source, destination in 
  // Implement here your transition logic, like that:
  // source.present(destination, animated: true, completion: nil)
}

// Setup module input.
.then { moduleInput in 
  moduleInput.configure(with: "Hello custom transition!")
}

Customize transition

For customize your transition you can change transition presentation and set animation.

Animate transition

This methods can animate your current transition.

.transition(animate: false)

Change presentation

Method to(preffered:), have responsobility for change presentation style. He work with UINavigationController, UISplitViewController, ModalPresentation and default presentation.

.to(preferred: TransitionStyle)

📌Supported styles:

  • Navigation style (push, pop, present)
    .to(preferred: .navigation(style: NavigationStyle))
  • Split style (detail, default)
    .to(preferred: .split(style: SplitStyle))
  • Modal style (UIModalTransitionStyle, UIModalPresentationStyle - standart UIKit's presentations styles.)
    .to(preferred: .modal(style: style: (transition: UIModalTransitionStyle, presentation: UIModalPresentationStyle)))

Configure you destination controller

Sometimes you need add additional dependency in your controller. For this case, will be add method apply(to:). That method return destination controller and you can configurate him.

try? transitionHandler
  .forSegue(identifier: "LiteRouteSegue", to: SecondViperViewControllerModuleInput.self)
  .apply(to: { controller in
    // configure your controller.
  })
  .then { moduleInput in
    // configure your module
  }
  

Transition on new storyboard

Also LiteRoute can transition on new storyboard instance like this:

// We remeber this class :)
func openModule(userIdentifier: String) {

  let storyboard = UIStoryboard(name: "NewStoryboard", bundle: Bundle.main)
  let factory = StoryboardFactory(storyboard: storyboard)

  try? transitionHandler

  // Initiates the opening of a new view controller from custom `UIStoryboard`.
  .forStoryboard(factory: factory, to: SecondViperViewControllerModuleInput.self)

	// Set animate for transition.
  .transition(animate: false)

  // View controller init block. 
  .then { moduleInput in 
    moduleInput.configure(with: userIdentifier)
  } // If you don't want initialize view controller, we should be use `.perform()`
}

Transition for Segue

You can initiate transition from UIStoryboardSegue like this:

func openModule(userIdentifier: String) {
  try? transitionHandler
       // Performs transition from segue and cast to need type
       .forSegue(identifier: "LiteRouteSegue", to: SecondViperViewControllerModuleInput.self)
       .then { moduleInput in
        moduleInput.setup(text: "Segue transition!")
      }
}

If you want to use EmbedSegue, need to add segue in storyboard, set class EmbedSegue and source view controller must conform protocol ViewContainerForEmbedSegue like this:

extension SourceViewController: ViewContainerForEmbedSegue {
    func containerViewForSegue(_ identifier: String) -> UIView {
        return embedView
    }
}

And you can initiate EmbedSegue transition like this:

func addEmbedModule() {
  try? transitionHandler
       .forSegue(identifier: "LiteRouteEmbedSegue", to: EmbedModuleInput.self)
       .perform()
}

Close current module

If you want initiate close current module, you should be use:

.closeCurrentModule()

And after this you can use perform() method for initiate close method.

Animate close transition

This methods can animate your current transition.

.transition(animate: false)

Note: Default true

Custom close style

If you wanna close pop controller or use popToRoot controller, you must perform method preferred(style:). That method have different styles for your close transition.

If you need call popToViewController(:animated) for your custom controller, you must perform method find(pop:).

try? transitionHandler
  .closeCurrentModule()
  .find(pop: { controller -> Bool
    return controller is MyCustomController
  })
  .preferred(style: .navigation(style: .findedPop))
  .perform()

Support UIViewControllerTransitioningDelegate

LiteRoute 2.0 start support UIViewControllerTransitioningDelegate for your transition. We can work with that use next methods:

.add(transitioningDelegate: UIViewControllerTransitioningDelegate)

Note

Thanks for watching.

literoute's People

Contributors

antigp avatar ayastrebov avatar ikloo avatar rinat-enikeev avatar spectraldragon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

literoute's Issues

Standart DI (via Configurator)

Привет!
У нас в проекте возникла проблема стандартного DI с помощью иницализатора и конфигуртора в рантайме приложения(необходимо было в модуле подменить интерактор при создании модуля). С этим отчасти справилась Storyboard factory(инициализацией нового контроллера в Router'е), но необходимо было дальше передать этот контроллер в LightRoute с настройками навигации/анимации/инпута.

Было придумано такое решение:

let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
let factory = StoryboardFactory(storyboard: storyboard, restorationId: viewControllerId)

guard let controller = factory.instantiateTransitionHandler as? ViewController else { return }
		
_ = ViewControllerModuleInitializer(viewController: controller, forLogin: true)
		
transitionHandler
	.toViewController(controller, to: ViewControllerModuleInput.self)
	.to(preferred: .navigationController(preferredStyle: .push))
	.then { moduleInput in
		moduleInput.configure(with: "configure module input")
        }

т.е. был добавлен метод toViewController<T>(_ destination: UIViewController, to type: T.Type) -> TransitionPromise<T> в source файлы пода.

Реализация метода выглядит так:

func toViewController<T>(_ destination: UIViewController, to type: T.Type) -> TransitionPromise<T> {
		let promise = TransitionPromise(root: self, destination: destination, for: type)
		
		// Default transition action.
		promise.postLintAction {
			self.present(destination, animated: true, completion: nil)
		}
		
		return promise
	}

На данный момент такой метод работает вполне отлично. Хотелось бы увидеть его в твоем поде. Если такое решение устраивает, то могу сделать пул реквест с изменениями. :)

Needs add tests to project

Right now project doesn't have anyone tests, and new features will have problem with integrating.
My be you could help us?

Проблема с подключением Pod-а.

Привет.
Почему-то при вот таком подключении pod "LightRoute" качается 2.1.19, при таком pod 'LightRoute', :git => 'https://github.com/SpectralDragon/LightRoute.git' качается 2.1.21 (то что надо). Есть очень большая необходимость в таком подключении pod 'LightRoute', чтоб выкачивалась версия 2.1.21 - без указания адреса репозитория. Можешь поправить ?

Module output

Как реализовать module output при переходе?

PopToRoot in NavigationController

Привет!
Я делал пул реквест с обновленным закрытием модулей по аналогии с тем, что есть уже(через TransitionPromise), но в обновлении я этого не нашел. В связи с этим у меня возникла такая проблема:
Как мне сделать переход к рутовому VC в navigationController's стеке без передачи controllerId?

И почему ты все таки решил оставить старую реализацию закрытия модуля(без TransitionPromise, без конфигурирования animated как в других методах, без выбора типа закрытия)?

LiteRoute is not compatible with Swift5

  • UIViewController.children -> UIViewController.childViewControllers
  • UIViewController.addChild(_:) -> UIViewController.addChildViewController(_:)
  • UIViewController.didMove(toParent:) -> UIViewController.didMove(toParentViewController:)

popViewController

В роутере есть переменная

weak var transitionHandler: TransitionHandler!

Для перехода на модуль

transitionHandler.forSegue(identifier: ...

Как сделать popViewController?

.transition(animate: false) has no effect

An example code:

        try? transitionHandler
            .forCurrentStoryboard(restorationId: "SplashViewController", to: SplashViewController.self)
            .transition(animate: false)
            .apply(to: { destination in
                destination.modalPresentationStyle = .custom
            })
            .add(transitioningDelegate: noFlashTransitionDelegate)
            .perform()

This will be always animated

StoryboardFactory question

Отличная работа, давно планирую начать делать свой проект на Viper в свободное от работы время, а это именно то что нужно, т.к наработки Rambler уже не актуальны, имхо.
Я часто использую один экран - один сторибоард благодаря этому, можно написать это:

class HomeViewController: UIViewController {
    static func storyboardInstance() -> HomeViewController? { 
        let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
        return storyboard.instantiateInitialViewController() as? HomeViewController 
    }
}

let homeViewController = HomeViewController.storyboardInstance()

Не знаю, подходит ли эта концепция для Viper c DI. Но я попробую объяснить свою точку зрения. В вашем примере есть такое:

private lazy var transitionModuleFactory: StoryboardFactoryProtocol = {
        let factory = StoryboardFactory(storyboard: self.mainStoryboard, restorationId: self.thirdModuleID)
        
        return factory
    }()

Однако, если мне нужен переход на другой сторибоард где только один экран, то это свойство будет ненужным. Можно перенести создание фабрики прямиком в метод:

let factory = StoryboardFactory(storyboard: self.thirdStoryboard)
		transitionHandler
            .forStoryboard(factory: factory).....

А можно пойти дальше и расширить ваш класс добавив "стандартную" factory в метод(Знаю что подобная инициализация объекта плохой пример):

    func forStoryboard<T>(storyboard:UIStoryboard, to type: T.Type) -> TransitionPromise<T> {
        return forStoryboard(factory: StoryboardFactory(storyboard: storyboard), to: type)
    }
    
    func forStoryboard<T>(factory: StoryboardFactoryProtocol, to type: T.Type) -> TransitionPromise<T> {
        
        let destination = factory.instantiateTransitionHandler
//...

Исходя из этого, можно сделать переход таким:

		transitionHandler
            .forStoryboard(storyboard: thirdStoryboard, to: ThirdModuleModuleInput.self)
            .to(preferred: TransitionStyle.navigationController(preferredStyle: .push))
			.then { moduleInput in
				moduleInput.configure(with: data)
		}

Это всего лишь идея улучшения функционала.

Navigation controller pop bug

Когда вызываешь pop функцию в LightRoute прилетает exception "Can't get pop controller in navigation controller stack." Контроллер в стеке 100% есть.
Метод такого вида:

try? transitionHandler
            .forCurrentStoryboard(resterationId: nextModuleId, to: RegistrationBaseModuleInput.self)
            .to(preferred: .navigationController(style: .pop))
            .then { moduleInput in
                moduleInput.configure(with: data.editFields)
        }

UPD. moduleInput имеет другой viewController, создается второй такой модуль.
Необходимо решение с destination именно чтобы получить moduleInput.

Через метод закрытия получилось получить необходимый модуль, но без moduleInput.

 try? transitionHandler.closeCurrentModule(animated: true)
			.find(pop: { controller -> Bool in
				return controller.restorationIdentifier == nextModuleId
			})
			.preferred(style: .navigationController(style: .findedPop))
			.perform()

Ошибка в назначении moduleOutput

Добрый день. Такая ошибка: сейчас в блоке .then, если вернуть указатель на moduleOutput, то он присваивается источнику вызова segue.source.moduleOutput = output (класс SegueTransitionNode), что в корне не правильно, - тут нужно чтобы было так self.destination?.moduleOutput = moduleOutput, как в классе GenericTransitionNode в методе, который перегружается в SegueTransitionNode. Из-за этого в блоке then по return нельзя использовать moduleOutput, приходится его передавать через метод конфигурации модуля (через moduleInput).

Поправить это не сложно: нужно всего лишь вместо segue.source.moduleOutput = output, написать segue.destination.moduleOutput = output в методе then класса SegueTransitionNode.

Поправьте, пожалуйста.

then does not called

my router of first module:
1

second module input protocol:
2

my second module presenter:
3

Update cocoapod to version 1.0.8

Hi. I'm so impressed with your work its make my router part pretty neat.
I saw you already merged PR about close module and bump that part to version 1.0.8.

Do you have any plan to move cocoapod to version 1.0.8 also? because now its still 1.0.6 so for now I have to point to master branch in podfile manually.

Thanks!

.then closures not called

Example:

MyModuleInput

protocol MyModuleInput: class {
    func configureModule(item: ARItemInfo)
}

Presetning module router:

            try self.transitionHandler!.forSegue(identifier: segueIdentifier, to: MyModuleInput.self).then({ (moduleInput) in
                moduleInput.configureModule(item: item)
            })

If MyModuleInput protocol is NOT defined as class, the .then block will not be invoked.
I think there must be some kind of warning or a check for this case

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.