React.js like Mixin. More powerful Protocol-Oriented Programming.

Related tags

UI swift ios mixins
Overview

Mixin 🍹

Version License Platform

Why?

Swift is Protocol-Oriented Programming, and it's more powerful by default implementations of extensions of protocols. You can mixin methods to classes like Ruby's Mixin.

However, iOS as a UI framework, objects like UIViewController have their own life cyle, if you can't listen life cyle methods, extensions as mixin don't really help.

For example, I write a protocol with extension to listen keyboard events

protocol KeyboardMixin {
    var keyboardHeight: CGFloat? { set get }
    func registerKeyboard()
    func deregisterKeyboard()
}

extension KeyboardMixin {
    func registerKeyboard() {
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillHide, object: nil, queue: nil) { [weak self] notification in
            self?.keyboardHeight = nil
        }
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil, queue: nil) { [weak self] notification in
            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                self?.keyboardHeight = keyboardSize.height
            }
        }
    }
    func deregisterKeyboard() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
}

But I still need to register and deregister by myself

class ViewController: UIViewController, KeyboardMixin {
    var keyboardHeight: CGFloat? {
        didSet { }
    }
    override func viewWillAppear(_ animated: Bool) {
        registerKeyboard()
    }
    override func viewWillDisappear(_ animated: Bool) {
        deregisterKeyboard()
    }
}

The problem is why can't I mixin something to existing methods e.g. UIViewController life cyle?

If you have programmed React.js, you'll find its Mixin mechanism is very useful. So I just copy the idea to iOS. After using this package, you can write a mixin like this.

public protocol KeyboardMixin: ViewControllerMixinable {
    var keyboardHeight: CGFloat? { set get }
}

public extension KeyboardMixin {
    private func registerKeyboard() {
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillHide, object: nil, queue: nil) { [weak self] notification in
            self?.keyboardHeight = nil
        }
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil, queue: nil) { [weak self] notification in
            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                self?.keyboardHeight = keyboardSize.height
            }
        }
    }
    private func deregisterKeyboard() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    fileprivate func viewWillAppear(_ animated: Bool) {
        registerKeyboard()
    }
    fileprivate func viewWillDisappear(_ animated: Bool) {
        deregisterKeyboard()
    }
}

And use it like below

class ViewController: UIViewController, KeyboardMixin {
    var keyboardHeight: CGFloat? {
        didSet { }
    }
    override func viewWillAppear(_ animated: Bool) {
        // Don't worry, you can still do things here...
    }
}

It can't be simpler!

How it works

This package uses iOS runtime to swizzle methods, so all override methods and mixins' methods will be called simultaneously.

Support

This package support mixin to

Example

Check out Example ViewController, it shows how amazing to use Mixin

Requirements

Only tested in Swift 4

Installation

Mixin is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Mixin'

Author

Howard Yang, [email protected]

License

Mixin is available under the MIT license. See the LICENSE file for more info.

You might also like...
Convenient domain specific language for writing programmatic UI built over UIKit and more.

XYKit Swifty and convenient domain specific language for creating programmatic UI in a more declarative way and more than that. Built on top of UIKit

🎸🎸🎸 Common categories for daily development. Such as  UIKit, Foundation, QuartzCore, Accelerate, OpenCV and more.
🎸🎸🎸 Common categories for daily development. Such as UIKit, Foundation, QuartzCore, Accelerate, OpenCV and more.

🎸🎸🎸 Common categories for daily development. Such as UIKit, Foundation, QuartzCore, Accelerate, OpenCV and more.

A set of frameworks making iOS development more fun

A set of frameworks making iOS development more fun, developed by N8ive Apps Frameworks InterfaceKit AuthKit CoreKit (in progress) NetworkKit (in prog

A fancy hexagonal layout for displaying data like your Apple Watch
A fancy hexagonal layout for displaying data like your Apple Watch

Hexacon is a new way to display content in your app like the Apple Watch SpringBoard Highly inspired by the work of lmmenge. Special thanks to zenly f

A horizontal scroll dial like Instagram.
A horizontal scroll dial like Instagram.

HorizontalDial Preview Requirements iOS 8.0+ Swift 5 Storyboard support Installation CocoaPods use_frameworks! pod "HorizontalDial" Manually To instal

You can dismiss modal viewcontroller like Facebook Messenger by pulling scrollview or navigationbar in Swift.
You can dismiss modal viewcontroller like Facebook Messenger by pulling scrollview or navigationbar in Swift.

PullToDismiss PullToDismiss provides dismiss modal viewcontroller function like Facebook Messenger by pulling scrollview or navigationbar with smooth

RangeSeedSlider provides a customizable range slider like a UISlider.
RangeSeedSlider provides a customizable range slider like a UISlider.

RangeSeekSlider Overview RangeSeekSlider provides a customizable range slider like a UISlider. This library is based on TomThorpe/TTRangeSlider (Objec

SAHistoryNavigationViewController realizes iOS task manager like UI in UINavigationContoller. Support 3D Touch!
SAHistoryNavigationViewController realizes iOS task manager like UI in UINavigationContoller. Support 3D Touch!

SAHistoryNavigationViewController Support 3D Touch for iOS9!! SAHistoryNavigationViewController realizes iOS task manager like UI in UINavigationConto

Full configurable spreadsheet view user interfaces for iOS applications. With this framework, you can easily create complex layouts like schedule, gantt chart or timetable as if you are using Excel.
Full configurable spreadsheet view user interfaces for iOS applications. With this framework, you can easily create complex layouts like schedule, gantt chart or timetable as if you are using Excel.

kishikawakatsumi/SpreadsheetView has moved! It is being actively maintained at bannzai/SpreadsheetView. This fork was created when the project was mov

Owner
Wan-Huang Yang
Goodnight co-founder. MS in CS at JHU
Wan-Huang Yang
URLEmbeddedView automatically caches the object that is confirmed the Open Graph Protocol.

URLEmbeddedView Features Simple interface for fetching Open Graph Data Be able to display Open Graph Data Automatically caching Open Graph Data Automa

Taiki Suzuki 643 Dec 20, 2022
Protocol to handle initial Loadings, Empty Views and Error Handling in a ViewController & views

StatusProvider Protocol to handle initial Loadings, Empty Views and Error Handling in a ViewController & views CocoaPods Podfile pod 'StatusProvider'

Mario Hahn 887 Dec 22, 2022
List tree data souce to display hierachical data structures in lists-like way. It's UI agnostic, just like view-model and doesn't depend on UI framework

SwiftListTreeDataSource List tree data souce to display hierachical data structures in lists-like way. It's UI agnostic, just like view-model, so can

Dzmitry Antonenka 26 Nov 26, 2022
macOS GUI Library for the Nim Programming Language

NimCocoa NimCocoa is an experimental implementation of a Native GUI for the Nim programming language running on macOS. Rather than rely on low level c

null 32 Dec 8, 2022
Swift programming language hackathon. Implementation of the main logic of working with an ATM in the Playground environment.

Hackaton-ATM-PJ04 Swift programming language hackathon. Implementation of the main logic of working with an ATM in the Playground environment. The tas

Raman Kozar 2 Oct 4, 2022
Powerful and easy-to-use vector graphics Swift library with SVG support

Macaw Powerful and easy-to-use vector graphics Swift library with SVG support We are a development agency building phenomenal apps. What is Macaw? Mac

Exyte 5.9k Jan 1, 2023
Stencil is a simple and powerful template language for Swift.

Stencil Stencil is a simple and powerful template language for Swift. It provides a syntax similar to Django and Mustache. If you're familiar with the

Stencil Project 2.2k Jan 4, 2023
A Powerful , Extensible CSS Parser written in pure Swift.

A Powerful , Extensible CSS Parser written in pure Swift. Basic Usage From CSS: #View { "width" : 118; "height" : 120.5; "color1" : "#888888"; "co

null 273 Sep 9, 2022
Custom emojis are a fun way to bring more life and customizability to your apps.

Custom emojis are a fun way to bring more life and customizability to your apps. They're available in some of the most popular apps, such as Slack, Di

Stream 244 Dec 11, 2022
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

Haoking 336 Nov 26, 2022