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...
iOS Logs, Events, And Plist Parser

iLEAPP iOS Logs, Events, And Plists Parser Details in blog post here: https://abrignoni.blogspot.com/2019/12/ileapp-ios-logs-events-and-properties.htm

BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

Pure Declarative Programming in Swift, Among Other Things

Basis The Basis is an exploration of pure declarative programming and reasoning in Swift. It by no means contains idiomatic code, but is instead inten

🗃 Powerful and easy to use Swift Query Builder for Vapor 3.
🗃 Powerful and easy to use Swift Query Builder for Vapor 3.

⚠️ This lib is DEPRECATED ⚠️ please use SwifQL with Bridges Quick Intro struct PublicUser: Codable { var name: String var petName: String

Swift-friendly API for a set of powerful Objective C runtime functions.
Swift-friendly API for a set of powerful Objective C runtime functions.

ObjectiveKit ObjectiveKit provides a Swift friendly API for a set of powerful Objective C runtime functions. Usage To use ObjectiveKit: Import Objecti

Created a Tic Tac Toe game with pure swift that runs within zsh shell.
Created a Tic Tac Toe game with pure swift that runs within zsh shell.

Swift TicTacToe Created a Tic Tac Toe game with pure swift that runs within zsh shell. The computer is actually really hard to beat and it ends up bei

Diff - Simple diffing library in pure Swift

Diff Simple diffing library in pure Swift. Installing You can use Carthage or Swift Package Manager to install Diff. Usage Start by importing the pack

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
A simple, but efficient CSV Parser, written in Swift.

CSV CSV.swift is a powerful swift library for parsing CSV files that supports reading as [String], [String: String] and Decodable, without sacrificing

Ben Koska 4 Nov 28, 2022
A parser combinator library written in the Swift programming language.

SwiftParsec SwiftParsec is a Swift port of the Parsec parser combinator library. It allows the creation of sophisticated parsers from a set of simple

David Dufresne 219 Nov 6, 2022
A utility that reminds your iPhone app's users to review the app written in pure Swift.

SwiftRater SwiftRater is a class that you can drop into any iPhone app that will help remind your users to review your app on the App Store/in your ap

Takeshi Fujiki 289 Dec 12, 2022
Super powerful remote config utility written in Swift (iOS, watchOS, tvOS, OSX)

Mission Control Super powerful remote config utility written in Swift (iOS, watchOS, tvOS, OSX) Brought to you by Have you ever wished you could chang

appculture 113 Sep 9, 2022
Swift Parser Combinator library inspired by NimbleParsec for Elixir.

SimpleParsec Simple parser combinator library for Swift inspired by NimbleParsec for Elixir. Each function in the library creates a Parser which can b

null 0 Dec 27, 2021
An SSH config parser library with a fancy API

The SshConfig makes it quick and easy to load, parse, and decode/encode the SSH configs. It also helps to resolve the properties by hostname and use them safely in your apps (thanks for Optional and static types in Swift).

Artem Labazin 8 Nov 25, 2022
.DS_Store file parser/viewer.

.DS_Store file parser/viewer.

JD Gadina 51 Dec 1, 2022
ParserCombinators - String Parser Construction Kit

ParserCombinators provides a set of elementary building blocks for deriving stru

Marcel Tesch 0 Jan 7, 2022
HxSTLParser is a basic STL parser capable of loading STL files into an SCNNode

HxSTLParser HxSTLParser is a basic STL parser capable of loading STL files into an SCNNode. Installing Via Carthage Just add it to your Cartfile githu

Victor 23 Dec 16, 2022
A result builder that build HTML parser and transform HTML elements to strongly-typed result, inspired by RegexBuilder.

HTMLParserBuilder A result builder that build HTML parser and transform HTML elements to strongly-typed result, inspired by RegexBuilder. Note: Captur

null 4 Aug 25, 2022