GithubHelp home page GithubHelp logo

stylekit's Introduction

alt text

Build Status Carthage compatible

StyleKit is a microframework that enables you to style your applications using a simple JSON file. Behind the scenes, StyleKit uses UIAppearance and some selector magic to apply the styles. You can also customize the parser for greater flexibility.

How does it work?

Create a JSON file in the following format

{
	"@headingFont": "HelveticaNeue-Bold:30.0",
	"UILabel": {
		"font": "@headingFont",
		"backgroundColor": "#000FFF"
	},
	"StyleKitDemo.SKView": {
		"StyleKitDemo.SKLabel": {
			"font": "HelveticaNeue-Bold:20.0",
			"backgroundColor": "#FFF000",
			"color": "#fff"
		},
		"StyleKitDemo.SKButton": {
			"font": "HelveticaNeue-Light:20.0",
			"titleColor:normal": "#FFFFFF",
			"titleColor:highlighted": "#000000"
		}
	},
	"StyleKitDemo.SKNavigationBar": {
		"titleTextAttributes": {
			"NSColor": "#000FFF",
			"NSFont": "@headingFont"
		}
	},
	"StyleKitDemo.SKTextField": {
		"font": "HelveticaNeue-Light:20.0",
		"textColor": "#000FFF"
	}
}

Load JSON file

AppDelegate.swift

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    if let styleFile = Bundle.main.url(forResource: "style", withExtension: "json") {
        StyleKit(fileUrl: styleFile)?.apply()
    }
    
    return true
}

On application launch the JSON file will be loaded and the styles applied.

The JSON file structure

Each object inside the JSON file should contain the name of the UIView as a key and the object inside should either contain the properties/functions that need to be set/called or another UIView, this will give you the ability to apply styles on views when contained in other views, an example of this would be the following.

{
	"UIButton": {
		"font": "HelveticaNeue-Bold:20.0"
	},
	"MyApp.LoginView": {
		"UIButton": {
			"font": "HelveticaNeue-Light:25.0"
		}
	}
}

This would apply HelveticaNeue-Bold with size 20 to all the UIButtons except the ones contained inside the LoginView class in your app.

Custom classes must be namespaced by the name of the module they are contained in. e.g. StyleKitDemo.SKTextField

Aliases

{
    "@mainFont": "HelveticaNeue-Bold:20.0",
    "@primaryColor": "#000FFF",
    "UIButton": {
        "font": "@mainFont"
    },
    "MyApp.LoginView": {
        "UIButton": {
            "font": "HelveticaNeue-Light:25.0",
            "titleColor:normal": "@primaryColor"
        }
    }
}

Bring Your Own Parser

StyleKit's initialiser supports passing a custom parser which should conform to the StyleParsable protocol.

Default Parser

class StyleParser: StyleParsable {

    func getStyle(forName name: String, value: AnyObject) -> AnyObject { 
        if let value = value as? String {
            if let font = FontHelper.parseFont(value) {
                return font
            } else if let color = ColorHelper.parseColor(value) {
                return color
            }
        }
        return value
    }
}

AppDelegate.swift

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    if let styleFile = Bundle.main.url(forResource: "style", withExtension: "json") {
        StyleKit(fileUrl: styleFile, styleParser: StyleParser())?.apply()
    }
    
    return true
}

Logging

By default, StyleKit will log any errors to the console. To customise the level of logging, you can pass a logLevel parameter as follows:

StyleKit(fileUrl: styleFile, logLevel: .debug)?.apply()

The levels of logging are:

  • .debug
  • .error (This is the default log level)
  • .severe
  • .none

How to install?

Carthage

Swift 3
github "146BC/StyleKit" ~> 0.6
Swift 4
github "146BC/StyleKit" ~> 0.7

CocoaPods

Add the 146BC Source

source 'https://github.com/146BC/Specs.git'
source 'https://github.com/CocoaPods/Specs.git'
Swift 3
pod 'StyleKit', '~> 0.6'
Swift 4
pod 'StyleKit', '~> 0.7'

stylekit's People

Contributors

jeanazzopardi avatar albinekcom avatar phimage avatar jakubpetrik avatar joekosowicz avatar stephenriolo avatar

Stargazers

ᴅɪᴍᴀ ᴅɪsᴀᴠʟᴇ avatar Maxim Raskevich avatar  avatar 谢东华 avatar pedoc avatar Yasin ATEŞ avatar  avatar  avatar Daeyeol Ryu avatar Kyrylo Gorbachov avatar  avatar BeiXiao avatar  avatar Cody Henshaw avatar Taotao Ma avatar Gurpreet avatar Boguś Łyczba Jr. avatar O. DEV avatar Shreyesh Arangath avatar pilgwon avatar Wonyoung Ju avatar Mohammed Elnaggar avatar Karim Ebrahem avatar  avatar Anshul Negi avatar  avatar Mark Dawson avatar Eric avatar  avatar  avatar İlker Kurtel avatar  avatar  avatar Rufat Babayev avatar Igor Kurilenko avatar Matt Whittaker avatar  avatar Jared Shenson avatar Krzysztof Koziol avatar oldbird avatar Leonardo Cavalcante avatar Illya Busigin avatar Rushton Pippin avatar Ryan avatar Tim Palade avatar shakesVan avatar surfsky avatar Rakhim Abdullayev avatar Dalton avatar Oktay I. avatar Aleksey Potapov avatar yoooooo avatar  avatar Archi avatar Jakub Truhlář avatar Travis Nguyen avatar Fan'小陆 avatar  avatar Anthony Ng avatar GY avatar foxsofter avatar wsliang avatar Florian COULON avatar  avatar Daniel Asher avatar Timur Kayumov avatar 王培岩 avatar Loic Tournier avatar Narcis avatar Mochamad Fariz Al Hazmi avatar Sasmito Adibowo avatar JoonKi Jin avatar Taehyun Park avatar Andrej avatar Alex avatar Artur Sagidulin avatar Leo Mehlig avatar wjiuxing avatar José Ney Guerrero avatar Aleš Kocur avatar Russell Daly avatar Florian Petit avatar Vadim Tikhonov avatar  avatar Dunya Kirkali avatar Maxim Tsvetkov avatar Portia avatar  avatar Yury Lebedev avatar Ali Bavafa avatar  avatar Ricki Y. HAN avatar Beach Cities Software, LLC avatar sp0cket avatar Karsten Gresch avatar Amir Hosseini avatar Donny Ho avatar Carlos Grossi avatar Hussein Jaber avatar  avatar

Watchers

 avatar Brent Hargrave avatar Magnus Renholm avatar Tales Pinheiro avatar Bernard Gatt avatar  avatar Russell Barnard avatar  avatar HoNooD avatar James Cloos avatar MohsinAli avatar Jagadeesh avatar Yonas Kolb avatar  avatar kenychen avatar loki avatar Peter Molnar avatar Carabineiro avatar kaneci avatar Roman Tkachev avatar Alin Ozi avatar NGUYEN VAN NHAN avatar  avatar Jeonggeun Kim avatar Victor Marcias avatar Hemant Mane avatar Jason Wilhelm avatar BrookYI avatar 王帅 avatar linqingmo avatar  avatar  avatar

stylekit's Issues

Travis CI

Travis CI would introduce stability and peace of mind when submitting pull requests, a hook needs to be setup so that every time a pull request is submitted or a commit is pushed the tests are executed automatically and a report of the result is generated.

Styles

Hi, great library!
It would be fantastic to be able to set something like a stylesproperty on a view which would be an array of strings stored as an associated object. These styles could then be referenced in the json. This way you could style something without making it a specific subclass.

Constants don't work

Example demo use version 0.3 and in style.json file you can find constants with prefix "@".
It doesn't work in latest release version 0.5.

Functions

In values we're proposing the introduction of a set of reserved keywords that will serve as functions, by version 1 there will be a number of functions available:

ImageURL

{
    "@logoImageURL": "https://avatars1.githubusercontent.com/u/17726261",
    "MyApp.LoginView": {
        "MyApp.LogoView": {
            "backgroundImage": "ImageURL(@logoImageURL)"
        }
    }
}

Gradient

{
    "@primaryColor": "#641E16",
    "@secondaryColor": "#78281F",
    "MyApp.LoginView": {
        "backgroundColor": "Gradient(style: 'Horizontal', locations: [0.9, 1.0], colors: [@primaryColor, @secondaryColor])"
    }
}

Alpha

{
    "@primaryColor": "#641E16",
    "MyApp.LoginView": {
        "UILabel": {
            "tintColor": "@primaryColor"
        },
        "UIButton": {
            "backgroundColor": "Alpha(@primaryColor, 80)"
        }
    }
}

In addition to these functions StyleKit will also provide a function registry so developers can add their own custom functions.

Live Reload

Live reload functionality will give developers the ability to reload styles at runtime. This enables developers to switch from one style to the other and opens up the possibility to create tools that hook up to the development environment and test styles on the fly without relaunching the application.

Supporting aliases

What I mean is instead of repeating yourself by copy-pasting for instance "HelveticaNeue-Bold:30.0" you would instead have an alias "bold30", or similarly "blue" : "#000FFF" . You could then have an aliases dict in the JSON that could be cross referenced at the start of parsing and aliases replaced with actual values.

Production ready

I'm considering using this project for an app, do you feel that it is production ready?

UIBarButtonItem support?

When trying to set the font on a UIBarButtonItem I constantly get unrecognized selector.
I'm sure I must be missing something obvious.

JSON code below

"UIBarButtonItem": {
        "titleTextAttributes": {
            "NSColor": "#99000000",
            "NSFont": "HelveticaNeue-Light:15.0"
        },
        "tintColor": "#000000"
}

Thanks for the library and suggestion,
Steve

Mixins

Mixins will give the ability to anyone styling the application to save and reuse styles, a mixin is created by treating an alias as a normal Class that requires styling, StyleKit will then associate all the styles contained in the block to that alias. Mixins would then be used by setting the mixins property that will be available on every component and passing in one or more aliases.

{
    "@primaryColor": "#641E16",
    "@secondaryColor": "#17202A",
    "@tertiaryColor": "#424949",
    "@textFieldStyle": {
        "font": "HelveticaNeue-Light:25.0",
        "color": "@primaryColor",
        "border": 0.5,
        "cornerRadius": 8.0
    },
    "MyApp.LoginView": {
        "MyApp.MainTextField": {
            "mixins": ["@textFieldStyle"],
            "backgroundColor": "@secondaryColor"
        },
        "MyApp.SecondaryTextField": {
            "mixins": ["@textFieldStyle"],
            "backgroundColor": "@tertiaryColor"
        }
    }
}

Better Test Coverage

The tests we have in place now are only checking whether JSON files are formatted properly, we need tests that make sure styles are being applied properly and that any errors are handled gracefully.

Aliases

In keys and values we're proposing the introduction of a reserved keyword @ that will be used to get and set aliases.

If a developer specifies @primaryColor as a key then the value associated with the key will be stored as an alias with the name @primaryColor, if on the other hand a value of @primaryColor is passed StyleKit will return the previously associated value.

{
    "@mainFont": "HelveticaNeue-Bold:20.0",
    "@primaryColor": "#000FFF",
    "UIButton": {
        "font": "@mainFont"
    },
    "MyApp.LoginView": {
        "UIButton": {
            "font": "HelveticaNeue-Light:25.0",
            "titleColor:normal": "@primaryColor"
        }
    }
}

Compilation issue with Xcode 8.3 : Type of expression is ambiguous without more context

There is some issues with last Xcode

.../StyleKit/StyleKit/Stylist.swift:104:98: Type of expression is ambiguous without more context
.../StyleKit/StyleKit/Stylist.swift:109:57: Type of expression is ambiguous without more context
.../StyleKit/StyleKit/Stylist.swift:114:116: Type of expression is ambiguous without more context
.../StyleKit/StyleKit/Stylist.swift:123:75: Type of expression is ambiguous without more context
.../StyleKit/StyleKit/Stylist.swift:130:98: Type of expression is ambiguous without more context
.../StyleKit/StyleKit/Stylist.swift:135:57: Type of expression is ambiguous without more context

For instance

self.currentComponent?.appearance(whenContainedInInstancesOf: viewStack).perform(Selector(modifiedSelector))

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.