A Powerful , Extensible CSS Parser written in pure Swift.

Overview


A Powerful , Extensible CSS Parser written in pure Swift.

Basic Usage

From CSS:

#View {
 "width" : 118;
 "height" : 120.5;
 "color1" : "#888888";
 "color2" : RGB(200,200,200);
 "color3" : RGB(200,200,200,0.5);
 "font1" : "Helvetica-Bold" 18;
 "font2" : "Cochin";
 "size" : 10 10;
 }

To Cocoa:

let width = css.int(selector: "#View", key: "width") // Int
let height = css.double(selector: "#View", key: "height") //Double
let color1 = css.color(selector: "#View", key: "color1") //UIColor
let font1  = css.font(selector: "#View", key: "font1") //UIFont
let font2 = css.font(selector: "#View", key: "font2", fontSize: 14) //UIFont
let size = testSwiftCSS.size(selector: "#View", key: "size") //CGsize

It's very easy to setup and parse CSS with SwiftCssParser:

//1.Get CSS file path
let path = Bundle.main.url(forResource: "cssFileNmae", withExtension: "css")
//2.Get parsed CSS
let css = SwiftCSS(CssFileURL: path)
//3.Use it
let width = css.int(selector: "#View", key: "width")

Extension

It's very easy to build your own Powerful, Flexiable CSS based solutions base on SwiftCssParser.

Example1: SwiftDeviceCss

​ In most cases, Auto Layout can help us calculates the size and location of our views. But in some cases, we need to set specifc size and location for our views based on device type (device's screen size) to accomplish the Pixel Perfect design.

​ So, we can use SwiftCssParser to get layout value from CSS file. Different Device has different configuration file.

public let SwiftDeviceCss = SwiftCssStyleSheet.deviceCss()

class SwiftCssStyleSheet {
    
    private enum ScreenSize {
        case _320_480 //iPhone4 etc.
        case _320_568 //iPhone5 etc.
        //iPhone6....
    }
    
    static private let screenSize: ScreenSize = {
        let screen = UIScreen.main
        let size = UIScreen.main.fixedCoordinateSpace.bounds.size
        switch (size.width,size.height) {
        case (320,640):
        	return ._320_480
        //......
        }
    }()
    
    static func deviceCss() -> SwiftCSS {
        switch self.screenSize {
        case ._320_480:
            return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone4"))
        case ._320_568:
            return SwiftCSS(CssFileURL: URL.CssURL(name: "iPhone5"))
        //......
        }
    }
    
}

Then just layout:

view.frame.size = SwiftDeviceCss.size(selector: "#View", key: "size")

Exeample2: SwiftCssTheme

We can also create a powerful theme manager base on SwiftCssParser.

For example, we want to create a night & day theme.

public class SwiftCssTheme {
    
    public static let updateThemeNotification = Notification.Name("SwiftCSSThemeUpdate")
    
    public enum Theme {
        case day
        case night
    }
    
    public static var theme: Theme = .day {
        didSet {
            switch theme {
            case .day:
                self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day"))
            case .night:
                self.themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "night"))
            }
            NotificationCenter.default.post(name: updateThemeNotification, object: nil)
        }
    }
    
    public static var themeCSS = SwiftCSS(CssFileURL: URL.CssURL(name: "day"))
}

If we want to be able to dynamically modify the background color of UIView:

extension UIView {
    
    private struct AssociatedKeys {
        static var selector = "themeColorSelector"
        static var key = "themeColorKey"
    }
    
    var backgroundColorCSS: (selector: String,key: String) {
        get {
        	let selector = //Use objc_getAssociatedObject to get value.....
        	let key = //.....
            return (selector,key)
        }
        
        set {
            let selector = newValue.selector
            let key = newValue.key
            
            //Use objc_setAssociatedObject to set value......   
            
            NotificationCenter.default.addObserver(self, selector: #selector(_cssUpdateBackgroundColor), name: SwiftCssTheme.updateThemeNotification, object: nil)
            
            _cssUpdateBackgroundColor()
        }
    }
    
    private dynamic func _cssUpdateBackgroundColor() {
        self.backgroundColor = SwiftCssTheme.themeCSS.color(selector: self.backgroundColorCSS.selector, key: self.backgroundColorCSS.key)
    }
}

Then, we just need to specify the background color's CSS selector and key:

self.view.backgroundColorCSS = ("#View","color")

Changing theme is even easier:

@IBAction func changeColor(_ sender: UIButton) {
    if SwiftCssTheme.theme == .day {
        SwiftCssTheme.theme = .night
    } else {
        SwiftCssTheme.theme = .day
    }
}

All the code and demo can be found in the project. Feel free to download and experiment. Advice and pull requests are welcome.

Installation

CocoaPods:

pod 'SwiftCssParser'

License

SwiftCssParser is under the MIT license.

You might also like...
⚓️ Declarative, extensible, powerful Auto Layout
⚓️ Declarative, extensible, powerful Auto Layout

EasyAnchor ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut m

CoreXLSX is a Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

Pure Swift 2.0 S-expression Parser

SwiftExP This is an S-expression parser written in pure Swift 2.0, where pure means without making any necessary usage of Foundation APIs at its core.

Jay - Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready.

Pure-Swift JSON parser & formatter. Fully streamable input and output. Linux & OS X ready. Replacement for NSJSONSerialization.

More powerful label, attributed string builder and text parser.

DDText More powerful label, attributed string builder and text parser. DDLabel More powerful label than UILabel, using TextKit. It supports features b

Fully customizable and extensible action sheet controller written in Swift
Fully customizable and extensible action sheet controller written in Swift

XLActionController By XMARTLABS. XLActionController is an extensible library to quickly create any custom action sheet controller. Examples The action

An extensible monitoring framework written in Swift

XestiMonitors Overview Reference Documentation Requirements Installation CocoaPods Carthage Swift Package Manager Usage Core Location Monitors Core Mo

Pure makes Pure DI easy in Swift.

Pure Pure makes Pure DI easy in Swift. This repository also introduces a way to do Pure DI in a Swift application. Table of Contents Background Pure D

Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web
Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web

Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work

AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.
AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

A powerful SwiftUI Architecture that merges Redux to the functional world of Swift. While bringing powerful workflows to streamline CoreML/Metal/IPFS usage in the Apple ecosystem.
A powerful SwiftUI Architecture that merges Redux to the functional world of Swift. While bringing powerful workflows to streamline CoreML/Metal/IPFS usage in the Apple ecosystem.

GraniteUI - v0.0 - WIP A powerful SwiftUI Architecture that merges Redux event handling and state management with functional programming. While bringi

An awesome Swift CSS DSL library using result builders.

An awesome Swift CSS DSL library using result builders.

📄 A Swift DSL for writing type-safe HTML/CSS in SwiftUI way

📄 swift-web-page (swep) Swep is a Swift DSL for writing type-safe HTML/CSS in SwiftUI way. Table of Contents Motivation Examples Safety Design FAQ In

Flexbox in Swift, using Facebook's css-layout.

SwiftBox A Swift wrapper around Facebook's implementation of CSS's flexbox. Example let parent = Node(size: CGSize(width: 300, height: 300),

Mongrel is a Swift and HTML hybrid with a bit of support for CSS and Javascript.

Mongrel is a Swift and HTML hybrid with a bit of support for CSS and Javascript. Using a declaritive style of programming, Mongrel makes writing HTML feel natural and easy. Mongrel also uses a SwiftUI like body structure allowing structs to be completely dedicated as an HTML page or element.

Declarative view styling in Swift. Inspired by CSS modules.
Declarative view styling in Swift. Inspired by CSS modules.

Gaikan gives you powerful styling capabilities using a declarative DSL in Swift. Inspired by React: CSS in JS and CSS modules. To style UIView(s) just

(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.
(Animate CSS) animations for iOS. An easy to use library of iOS animations. As easy to use as an easy thing.

wobbly See Wobbly in action (examples) Add a drop of honey 🍯 to your project wobbly has a bunch of cool, fun, and easy to use iOS animations for you

Elm-parcel-capacitor - A sample setup to build an app with Elm, Capacitor, Parcel and Tailwind CSS

Elm, Capacitor, Parcel and Tailwindcss This project is a sample setup to build a

Comments
  • Make a framework?

    Make a framework?

    Hi, Will you later package it as frameworks usable with SPM, carthage and cocoapod ie. separate demo application code on file system like you do in xcode using group, ...

    opened by phimage 1
  • CssLexer.Token enum doesn't contain URL type

    CssLexer.Token enum doesn't contain URL type

    Wanted to parse background-image atribute which should contain URL in some cases https://developer.mozilla.org/en-US/docs/Web/CSS/url() https://www.w3schools.com/cssref/pr_background-image.asp

    but it is not present

    opened by kyzmitch 0
  • Can't add over CocoaPods

    Can't add over CocoaPods

    Hi,

    I wanted to use your framework, but it seems usual pod install doesn't work and even pod repo update didn't help. Also tried to add new source of podspec to Podfile like: source 'https://github.com/100mango/SwiftCssParser.git'

    and after that it is different error:

    [!] An unexpected version directory `Assets.xcassets` was encountered for the `/Users/homedir/.cocoapods/repos/100mango/SwiftCssParser` Pod in the `SwiftCssParser` repository.
    
    opened by kyzmitch 1
Releases(0.1.0)
Owner
null
An RSS, Atom and JSON Feed parser written in Swift

Features Atom RSS 0.90, 0.91, 1.00, 2.00 JSON Namespaces Dublin Core Syndication Content Media RSS iTunes Podcasting Tags Documentation Unit Test Cove

Nuno Dias 1k Jan 7, 2023
Recursive Length Prefix encoding written in Swift

RLPSwift This is a basic Swift implementation of Recursive Length Prefix Encoding, a serialisation method for encoding arbitrarily structured binary d

bitfwd community 22 Oct 6, 2020
Swift wrappers for the tree-sitter incremental parsing system

SwiftTreeSitter Swift wrappers for the tree-sitter incremental parsing system. Remember that tree-sitter has both runtime and per-language dependencie

Chime 153 Dec 8, 2022
WKZombie is a Swift framework for iOS/OSX to navigate within websites and collect data without the need of User Interface or API, also known as Headless browser.

WKZombie WKZombie is an iOS/OSX web-browser without a graphical user interface. It was developed as an experiment in order to familiarize myself with

Mathias Köhnke 1.1k Dec 16, 2022
A Powerful , Extensible CSS Parser written in pure Swift.

A Powerful , Extensible CSS Parser written in pure Swift.

null 273 Sep 9, 2022
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
A lightweight CSS parser for parsing and creating CSS stylesheets

SwiftCSSParser A lightweight CSS parser for Swift that uses cssparser (cpp) under the hood. Basic usage Here's a simple code snippet to get you starte

null 9 Jul 20, 2022
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

Nabil Chatbi 3.7k Jan 6, 2023
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

Nabil Chatbi 3.7k Dec 28, 2022
A fast & lightweight XML & HTML parser in Swift with XPath & CSS support

Fuzi (斧子) A fast & lightweight XML/HTML parser in Swift that makes your life easier. [Documentation] Fuzi is based on a Swift port of Mattt Thompson's

Ce Zheng 994 Jan 2, 2023